Tuesday, January 29, 2013

Object Creation and initialization in Objective C

COCO suggest to use alloc and init method for object creation.
alloc:- allocates the required memory for the object and initializes memory content to zero.
init :- will initializes the object data members.

alloc and init should be chaining like this
Rect *rect=[[Rect alloc] init];
should not like

Rect *rect=[Rect alloc];
[rect init];
Reason for this is init sometimes return the object which is not same as on which method get called so.
init sometime create new object sometime that object require extra space eg. in String object .


When writing your custom init method always call [super init] to initialize the super classes.
as mentioned earlier init may return the different object so always call 
self= [super init];// as subclassing will take part of it in main derived class.


There is copy method which creates  brand new object and to make the new object same as on which it is called.

0 comments:

Post a Comment

About

Powered by Blogger.