4

I am writing a simple tabbed iOS app. It has 3 tabs each with its own view controller. In each view controller I declare a variable of the same name:

float nitriteLevel;

But when I make a change to the value of nitriteLevel in one VC it also changes the value of nitriteLevel in the others. As I understand it, this shouldn't be, they should be completely independent & unrelated. What might I have done wrong?

jessehouwing
  • 106,458
  • 22
  • 256
  • 341
  • 3
    Have you made it a global variable by mistake? – tc. Jan 14 '13 at 23:40
  • 1
    How are you declaring the variable? Like this? `@property (nonatomic) float nitriteLevel;` ? – MaxGabriel Jan 14 '13 at 23:41
  • I declared it as above (no *property or nonatomic) and it was declared between *interface and *implementation. Does this make it global? Just tried moving it inside @implementation and same behavior. (I thought there are no global variables in Objective-C?) – user1975122 Jan 15 '13 at 14:27

1 Answers1

3

Do you declare it in the middle of the implementation section? Or even outside any @... @end block? If so then you made it global. That is possible because beneath Objective-C there is Ansi C.

For a private instance variable do the following: MyClassName.h file:

@interface MyClassName : ItsSuperclassName <SomeProtocol> {
    float nitriteLevel;
}

// if you want it private then there is no need to declare a property. 

@end

MyClasseName.m file:

@implementation

// These days there is no need to synthesize always each property.
// They can be auto-synthesized. 
// However, it is not a property, cannot be synthesized and therefore there is no getter or setter. 

    -(void) someMehtod {

        self->nitriteLevel = 0.0f;  //This is how you access it. 
        float someValue2 = self->nitriteLevel; // That is fine. 

        self.nitriteLevel = 0.0f; // This does not even compile. 
        [self setNitriteLevel: 0.0f]; //Neither this works. 
        float someValue2 = self.nitriteLevel; // nope
        float someValue3 = [self setNitriteLevel]; // no chance

    }
@end

I am not 100% positive about the following: This type of variable is not being initialized automatically. You cannot use float nitriteLevel = 0.0f; at that point. Make sure that you initialize it in the init method. Depending on your stile initialize them latest in viewDidLoad (in View Controllers).

Hermann Klecker
  • 14,039
  • 5
  • 48
  • 71