Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

xcode

instance

- (id)init{
    if(![super init]){
        return nil;
    }
    _rssItems = [[NSMutableArray alloc]init];
    return self;
}

If I analyze my project I get this warning:

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

What do I have to change?

Thanks!

like image 463
AmiiQo Avatar asked Jan 21 '12 15:01

AmiiQo


1 Answers

Nowadays, Apple's official recommendation is:

- (id)init{
    self = [super init];
    if(self){
        _rssItems = [[NSMutableArray alloc]init];
    }
    return self;
}

The idea is that init (in particular, in this case, [super init]) is allowed to return an object other than self, and the expected behavior in that case is to work with that object instead--the easiest way to deal with this is to just set self to whatever super returns. Also note that return self; works fine whether self is nil or not, hence the reversal of your if.

Of course, most classes don't perform this switching trick--but this is good practice anyway because Apple expects everyone to be using this exact pattern for their init, so even if your subclass currently works without assigning to self, they could easily change that behavior in the future without warning.

like image 166
andyvn22 Avatar answered Nov 20 '22 07:11

andyvn22