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

拥有回忆 提交于 2019-12-06 18:20:05

问题


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?


回答1:


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




回答2:


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.




回答3:


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



来源:https://stackoverflow.com/questions/9970864/do-i-need-to-call-super-init-or-super-initwithcoder-etc-for-nsobject

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!