Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do I need to call [super init] or [super initWithCoder], etc for NSObject

Typically when I subclass from a UI class I will call the superclass initializer of interest. However, I'm not sure of the implementation details of NSObject, and it seems like there's not much going on in terms of member vars, so I wonder: do I need to call [super init] if my subclass extends NSObject?

like image 662
tacos_tacos_tacos Avatar asked Apr 02 '12 04:04

tacos_tacos_tacos


3 Answers

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

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

Because it is documented and there's probably already a bunch of code that relies on it, that fact is highly unlikely to change in future versions of Mac OS X.

Edit: BoltClock's a Unicorn brings up a point that I would like to make more hyperbolic: the total time saved by not calling -[NSObject init] for everyone ever running your program is unlikely to ever exceed the debugging time that you'd incur if you ever change the superclass for your class to something other than NSObject and forget to add a call to [super init].

like image 156
John Calsbeek Avatar answered Nov 16 '22 19:11

John Calsbeek


From the documentation, it doesn't appear to do any initialization at all:

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

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

like image 6
BoltClock Avatar answered Nov 16 '22 18:11

BoltClock


Just call through one of super's designated initializers in your implementation because you should just do what is clear and correct.

like image 1
justin Avatar answered Nov 16 '22 18:11

justin