I need to call [super init] or [super initWithCoder] etc. For NSObject

Usually, when I subclass a UI class, I will call an interesting superclass initializer. However, I'm not sure about the details of the NSObject implementation, and it seems that there is not much going on in terms of member classes, so I wonder if I need to call [super init] if my subclass extends NSObject

+8
inheritance ios objective-c superclass nsobject
source share
3 answers

Technically, no. The documentation for -[NSObject init] says that

The init method defined in the NSObject class NSObject not initialize; it just returns self .

Since it is documented and there probably already exists a bunch of code that builds on it, this fact is unlikely to change in future versions of Mac OS X.

Edit: BoltClock the Unicorn raises a point that I would like to make more hyperbolic: the total time saved without calling -[NSObject init] for anyone who has ever run your program, is unlikely to ever exceed the debug time that you would have suffered if you ever change the superclass for your class to something other than NSObject and forget to add a call [super init] .

+8
source share

From the documentation, it does not perform any initializations at all:

The init method defined in the NSObject class does not initialize; it just returns self .

I suppose it would be harmless not to call [super init] , but there is no reason not to follow the conventions and, you know, call it in your subclass anyway. For example, your subclass may end up inheriting from another class in the future, which may contain the initialization logic in its own -init method, which your subclass will then require.

+4
source share

Just call one of the super assigned initializers in your implementation, because you should just do what is clear and correct.

0
source share

All Articles