对象 - 当'self'未设置为'[(super或self)init ...]的结果时使用的实例变量

问题描述 投票:5回答:2

我已经问了一个类似的问题,但我仍然看不出问题?

-(id)initWithKeyPadType: (int)value
{
    [self setKeyPadType:value];
    self = [self init];
    if( self != nil )
    {
        //self.intKeyPadType = value;

    }
    return self;
}

- (id)init {

    NSNumberFormatter *formatter = [[[NSNumberFormatter alloc] init] 
                                                              autorelease];
    decimalSymbol = [formatter decimalSeparator];
....

警告来自Instance variable used while 'self' is not set to the result of '[(super or self) init...]'上方的一行

objective-c xcode cocoa-touch analyzer
2个回答
4
投票

你要做的是技术上没问题,但在某个阶段你需要调用[super init]。如果你的类的init方法做了许多其他initWith...方法使用的常见初始化,那么把你的[super init]放在那里。此外,在尝试使用实例变量之前,请始终确保该类已经是init'd。

- (id) initWithKeyPadType: (int)value
{
    self = [self init]; // invoke common initialisation
    if( self != nil )
    {
        [self setKeyPadType:value];
    }
    return self;
}

- (id) init
{
    self = [super init]; // invoke NSObject initialisation (or whoever superclass is)
    if (!self) return nil;

    NSNumberFormatter *formatter = [[[NSNumberFormatter alloc] init] 
                                                          autorelease];
    decimalSymbol = [formatter decimalSeparator];

    ...

2
投票

警告意味着它所说的。您正在为decimalSymbol分配一些东西,这是一个实例变量,但此时没有实例。你需要一个

self = [super init];

在init方法的开始。在某些时候必须创建对象,在某些时候这必须回调NSObject(通过一系列超级内容)。

© www.soinside.com 2019 - 2024. All rights reserved.