Eduardo Costa
Eduardo Costa

Reputation: 1994

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!

Upvotes: 5

Views: 1106

Answers (2)

jesper
jesper

Reputation: 11

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.

Upvotes: 1

Nick Hutchinson
Nick Hutchinson

Reputation: 5189

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?

Upvotes: 3

Related Questions