Quantcast
Viewing all articles
Browse latest Browse all 10

Designated Initializers in Objective C

Object construction in Objective C is a two phase procedure. First the object has to be allocated in memory, hence the ‘alloc’ message we always see when a object is invoked this way (and not for example via a ‘get…’, which would be a Factory):

MyObject* o = [[MyObject alloc] init];

Second phase involves object initialization which is quite similar to what would be a constructor in C++. When we implement method ‘init’ (which is just a convention) we have to take care on superclass designated initializer . But, what is a designated initializer at all?

Designated initializer is the method that best set up our object between all initializer methods. An example:

- (id) init:
- (id) initWithColor:(NSColor*)color;
- (id) initWithColor:(NSColor*)color andSize:(NSInteger)size;

What method do you think is the most complete?

Our third method includes two parameter while the other only one or none.

Now, we got a pattern that you are going to see every time you implement your own objects:

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

This is the most basic method. It neither do variable initialization nor call other initializers. It just call its superclass initializer, check its got a valid pointer back (thus not nil) and return self.

But if we got any other initializer methods we must call our most complete initializer. This is the designated initializer. So instead of our light ‘init’ tiny method we would have to call initWithColor:andSize:

- (id) init
{
NSColor* color = [NSColor greenColor];
NSInteger size = 30;
return [self initWithColor:color andSize:size];
}

and in our initWithColor:andSize:

- (id) initWithColor:(NSColor*)color andSize:(NSInteger)size
{
if (self = [super init]) {
_color = [color retain];
_size = size;
}
return self
}

Image may be NSFW.
Clik here to view.
Image may be NSFW.
Clik here to view.

Viewing all articles
Browse latest Browse all 10

Trending Articles