Jules
Jules

Reputation: 7776

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

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

Upvotes: 5

Views: 3152

Answers (2)

dreamlax
dreamlax

Reputation: 95355

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

    ...

Upvotes: 4

jrturton
jrturton

Reputation: 119272

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).

Upvotes: 2

Related Questions