For aesthetic reasons, I decided to change this:
if ((self = [super init])) {
开发者_StackOverflow中文版// 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!
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?
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.
精彩评论