Tuesday, 14 January 2014

Designated Initializers in Objective - C

Object construction in Objective C is a two phase procedure:--->

1.  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):

2. 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 .

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

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

- (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

No comments:

Post a Comment