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!

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


could someone help me understand this -(instancetype)init method ???

Right i'm doing ios objective c and we've came across this piece of code, could someone please explain why we use -(instancetype) for the type first of all, why we are initalising super and assigning it to self, and why on earth we check for self? How is self going to be a bool value? self is simply the class in which this piece of code lies within isn't it?

-(instancetype)init { self = [super init]; if(self) { }

return self; }

Cheers... i'm a noobie in ios so would be great for someone to explain in it extremely simple terms.

1 Answer

J.D. Sandifer
J.D. Sandifer
18,813 Points

Dylan, here's a basic overview of this. Please ask more questions if you'd like more info on a particular item:

-(instancetype) - This is the return identifier saying what will be returned by this method. The instancetype name means this method will return an instance of the class which contains this method.

init - This is the designated initializer method for the object. It's purpose is to setup the object.

self = [super init]; - Because Objective-C is Object Oriented, objects are part of an object tree and inherit from parent objects. There's a base object that everything inherits from even if no specific parent objects are defined.

This call to super is calling the parent object's designated initializer (init again) so all the inherited features are setup. In simple objects, this will just be the default properties and methods that apply to all objects.

if(self) { } - This is a check to make sure the object being initialized was properly setup. Only after we're sure we have a valid object, can we start doing things like setting member variables and so on. (We would do those kinds of things inside this if clause.)

return self; - this returns the valid object - or nil if something went wrong. This typically would be assigned to the variable on the left hand of the calling expression: object in a line like this. NSObject *object = [[NSObject alloc] init];