ios – 不同视图控制器中的同名变量

前端之家收集整理的这篇文章主要介绍了ios – 不同视图控制器中的同名变量前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在编写一个简单的标签式iOS应用程序.它有3个标签,每个标签都有自己的视图控制器.在每个视图控制器中,我声明一个同名的变量:

float nitriteLevel;

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

解决方法

您是否在实施部分的中间声明了它?甚至在@ … @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中).

猜你在找的Xcode相关文章