4

我正在编写一个简单的选项卡式 iOS 应用程序。它有 3 个选项卡,每个选项卡都有自己的视图控制器。在每个视图控制器中,我声明一个同名变量:

float nitriteLevel;

但是,当我在一个 VC 中更改 nitriteLevel 的值时,它也会更改其他 VC 中 nitriteLevel 的值。据我了解,这不应该是,它们应该是完全独立且不相关的。我可能做错了什么?

4

1 回答 1

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).

于 2013-01-15T00:09:56.917 回答