Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does ((self=[super init]]) work, but (!(self=[super init])) doesn't?

For aesthetic reasons, I decided to change this:

if ((self = [super init])) {
    // init self
}
return self;

Into this:

if (!(self = [super init])) return nil;
// init self
return self;

In theory, they do the same thing. The first one is the classic way, simply works. Debugging the second one, I found that it almost worked. The "if" does it right, the init code also, but, after returning "self", the debugger get back to the "if" and returns nil!

All classes I made with the second one I'm reverting to use the "correct" way because they where initing with nil, but I really want to know why does it behaves like that! I'm afraid that this may be the result of something else wrong!

like image 497
Eduardo Costa Avatar asked Oct 12 '22 03:10

Eduardo Costa


2 Answers

There's absolutely no difference between your two versions other than aesthetic preference, so something else must be going wrong. Perhaps you should post your whole init method?

like image 144
Nick Hutchinson Avatar answered Nov 19 '22 19:11

Nick Hutchinson


I created a test class for this, with the following init method:

- (id)init
{
    if (!(self = [super init])) return nil;
    [self setText:@"foo"];
    return self;
}

It initializes as expected, and I can access the text property. So as Nick pointed out, something else must be malfunctioning.

like image 36
jesper Avatar answered Nov 19 '22 21:11

jesper