nytimes / objective-c-style-guide

The Objective-C Style Guide used by The New York Times

Home Page:http://open.blogs.nytimes.com/2013/08/01/objectively-stylish/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Ivars should be directly accessed in init'ers

davedelong opened this issue · comments

Right now the guide simply says to use direct ivar access in dealloc. You should also directly access ivars in init* methods. More generally, you shouldn't really be invoking any method inside init* or dealloc methods. Other methods (including accessors that may be overridden) may expecting the object to be in a fully constructed state. When you're inside one of these methods, that is not the case.

More generally, you shouldn't really be invoking any method inside init* or dealloc methods

Care to elaborate?

If you're trying to be as defensive as possible, then you have to operate under the assumption that someone may have subclassed the class and overridden your public methods. These overrides may be assuming that when the method is invoked, all of the properties and ivars and everything are in a consistent and fully-initialized state.

So, if your initializer or dealloc method causes one of these overridden methods to be executed, then the logic of the method may do something incorrect. The best case scenario is that it works as intended. The worst case scenario is that you do something like dereference a NULL pointer or index beyond the bounds of an array or cause some data to become corrupted, etc.

Whilst you're inside an initializer or dealloc method, your object is in an inconsistent state. Thus, if you're trying to be as defensive as possible, you should avoid invoking methods that might be making assumptions about the state of the object.

commented

Hey @davedelong. Thanks for the great writeup. This is now fixed.