Obj-, Instance variable used when 'self' is not set to the result of '[(super or self) init…]'

℡╲_俬逩灬. 提交于 2019-12-22 07:15:07

问题


I asked a similar question to this already, but I still can't see the problem?

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

The warning comes from the line above Instance variable used while 'self' is not set to the result of '[(super or self) init...]'


回答1:


What you are trying to do is technically OK, but at some stage you need to invoke [super init]. If your class's init method does a lot of common initialisation that other initWith... methods utilise, then put your [super init] in there. Also, always make sure that the class has been init'd before trying to play around with instance variables.

- (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:


The warning means what it says. You are assigning something to decimalSymbol, which is an instance variable, but at that point there is no instance. You need a

self = [super init];

At the start of your init method. At some point the object has to be created, at some point this has to call back to NSObject (via a chain of super inits).



来源:https://stackoverflow.com/questions/8086996/obj-instance-variable-used-when-self-is-not-set-to-the-result-of-super-or

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!