user3124010
user3124010

Reputation:

What happens if you don't nil-check [super init] and try to initialize nil?

I know this has been discussed previously, in this question for instance: In Objective-C why should I check if self = [super init] is not nil?

- (instancetype)init
{
    self = [super init];    // Is potentially nil

    if (self)
    {
        // Initialization code here…
    }

    return self;
}

I understand that self might be nil, but why does that matter? All answeres I've seen just say that self might be nil but do not explain why it matters. If you send a message to nil nothing will happen. You don't nil-check in any other code (except in some cases) so why do you need to do it in init?

Upvotes: 1

Views: 171

Answers (2)

If you send a message to nil nothing will happen.

That's correct, because the runtime (messenger function) checks for nil before actually calling the method.

However, if you set self to nil while it's in the middle of a method call, any direct instance variable access will trigger a null pointer dereference:

self.myVar = ...;  // fine
_myVar = ...;     // fine

self = nil;

self.myVar = ...;  // fine
_myVar = ...;     // wrong

Upvotes: 1

Wain
Wain

Reputation: 119041

Partly convention, partly you're right, but it does depend on what you're going to setup using self.

In some cases you will be doing a lot of configuration, and creating all of that configuration when it won't actually be used is wasteful.

In some cases you may be passing nil to some configuration that will raise an exception when you do so, so checking and not making that call is sensible.

Following the convention is the safe and appropriate approach to take, and it really doesn't cost you anything (it's created for you by the template code).

Upvotes: 0

Related Questions