我正在编写一个简单的标签式iOS应用。它有3个标签,每个标签都有自己的视图控制器。在每个视图控制器中,我声明一个同名的变量:
float nitriteLevel;
但是当我在一个VC中更改nitriteLevel的值时,它也会更改其他中的nitriteLevel的值。据我所知,这不应该是,它们应该是完全独立的。无关。我可能做错了什么?
答案 0 :(得分:3)
您是否在实施部分的中间声明了它?甚至在@ ... @end块之外? 如果是这样,那你就把它变成了全局这是可能的,因为在Objective-C下面有Ansi C.
对于私有实例变量,请执行以下操作: MyClassName.h文件:
@interface MyClassName : ItsSuperclassName <SomeProtocol> {
float nitriteLevel;
}
// if you want it private then there is no need to declare a property.
@end
MyClasseName.m文件:
@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
我对以下内容并非100%肯定:此类型的变量未自动初始化。此时您无法使用float nitriteLevel = 0.0f;
。确保在init方法中初始化它。根据你的阶梯,在viewDidLoad中初始化它们(在View Controllers中)。