5

我已经问过类似的问题,但我仍然看不到问题?

-(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...]'

4

2 回答 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];

    ...
于 2011-11-10T22:25:24.247 回答
2

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

self = [super init];

在您的 init 方法开始时。在某些时候必须创建对象,在某些时候必须回调 NSObject(通过超级初始化链)。

于 2011-11-10T22:12:06.603 回答