开发者

Creating constructors in Objective-C

开发者 https://www.devze.com 2023-03-17 13:25 出处:网络
Why do we always do this when creating 开发者_如何学JAVAconstructors in Objective C? self = [super init];

Why do we always do this when creating 开发者_如何学JAVAconstructors in Objective C?

self = [super init];
if ( self ) {
    //Initialization code here
}


you can create constructor and destructor in objective-c with

-(id) init
{
    self = [super init];
    if(self)
    {
       //do something
    }
    return self;
}
-(void) dealloc
{
   [super dealloc];
}


We reassign to self because [super init] is allowed to return a different object than the one it was called on. We if (self) because [super init] is allowed to return nil.


self is a class based on some superclass (e.g. UIViewController, NSObject - see your interface file to be sure which one). The superclass might need some form of initialization in order for the subclass to work as expected. So by first initializing the superclass we make sure default properties and the like are set. Without initializing the superclass first, we might experience some very unexpected behavior, especially in more complex objects like ViewControllers and the like.


Read this apple document on initialization http://developer.apple.com/library/mac/#documentation/cocoa/Conceptual/ObjectiveC/Chapters/ocAllocInit.html

0

精彩评论

暂无评论...
验证码 换一张
取 消