Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS

Eric M
Eric M
2,242 Points

Why check `if (self)` before setting up the instance?

Not much explanation was given, and I'd love to know more. When would [super init] on an NSObject fail? How should you handle a failure if one happens?

Eric M
Eric M
2,242 Points

I read this. All I see is FUD and dogma: http://stackoverflow.com/questions/22608435/what-happens-if-we-dont-check-for-if-self-in-init-methods

The answers say things like "If something goes wrong it makes no sense to continue". If something went wrong with the super init, wouldn't this be a crash-causing error? I don't understand the point.

We don't check the return of every library method... why this one?

1 Answer

Eric M
Eric M
2,242 Points

The other SO answers are better: http://stackoverflow.com/questions/1287950/in-objective-c-why-should-i-check-if-self-super-init-is-not-nil

I guess all these cases fail:

[[NSData alloc] initWithContentsOfFile:@"this/path/doesn't/exist/"];
[[NSImage alloc] initWithContentsOfFile:@"unsupportedFormat.sjt"];
[NSImage imageNamed:@"AnImageThatIsntInTheImageCache"];

This particular idiom is standard because it works in all cases. While uncommon, there will be cases where... [super init] ...will return nil, thus requiring the nil check so that your code doesn't try to initialize an instance variable slot that no longer exists.

Sounds like init on an NSObject should never fail, and people just do it as standard practice.