13

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?

tacos_tacos_tacos
  • 10,277
  • 11
  • 73
  • 126

3 Answers3

12

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].

Community
  • 1
  • 1
John Calsbeek
  • 35,947
  • 7
  • 94
  • 101
6

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.

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
1

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

justin
  • 104,054
  • 14
  • 179
  • 226