开发者

Use of self = [super init] in custom init method of NSObject subclass

开发者 https://www.devze.com 2023-04-13 05:40 出处:网络
I am subclassing NSObject @interface MyClass : NSObject { } -(id)customInit; @end and implementing a custom init method in it,

I am subclassing NSObject

@interface MyClass : NSObject {

}
-(id)customInit;
@end

and implementing a custom init method in it,

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

and creating an instance of MyClass as below

MyClass *myClassInstance = [[MyClass alloc]customInit];

No开发者_StackOverfloww my question is, what will I miss if I use an customInit method without self = [super init]; like below,

  -(id)customInit
    {
       return self;
    }

Will I miss anything from the NSObject class which is the super class? Thanks


No, you won't miss anything. From the documentation:

The init method defined in the NSObject class does no initialization; it simply returns self.

But, I would still recommend calling self = [super init] in order to future proof your code in case you ever decide to change the base class, for example.


If I don't [super init] in my customInit method, I will be missing the work done by the init method of NSObject. But otherwise I will have access to all the methods of super class and its protocols as I am inheriting it.

0

精彩评论

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

关注公众号