10

Possible Duplicate:
In Objective-C why should I check if self = [super init] is not nil?

In Objective-C book i am reading, it is said that when [init] message is sent to NSObject, on occasion it may return nil and we should check the return value, before sending more messages to what may end up being a nil.

self = [super init];

if (self) {
 do stuff
}

I ask you though, what needs to happen for an NSObject to not be able to init itself?

Edit: Question specifically deals with an instance where YourClass:NSObject.

Community
  • 1
  • 1
James Raitsev
  • 92,517
  • 154
  • 335
  • 470

1 Answers1

8

NSObject itself will never return nil on init, however other classes that inherit from it might, so it's considered good practice to always check the return value of init. For example, this will return nil:

 [[NSData alloc] initWithContentsOfFile:@"path/to/a/file/that/does/not/exist"];
EdoDodo
  • 8,220
  • 3
  • 24
  • 30
  • Thanks! I suppose that for classes where `[super init]` is never `nil`, it's unnecessary to put that check. This way you could, for example: `return [super initWithFoo:X baz:Y];` – Ferran Maylinch Apr 25 '17 at 10:11