Skip to content
This repository has been archived by the owner on May 9, 2023. It is now read-only.

Ivars should be directly accessed in init'ers #6

Closed
davedelong opened this issue Aug 2, 2013 · 3 comments · Fixed by #16
Closed

Ivars should be directly accessed in init'ers #6

davedelong opened this issue Aug 2, 2013 · 3 comments · Fixed by #16
Labels

Comments

@davedelong
Copy link

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.

@xissburg
Copy link

xissburg commented Aug 2, 2013

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

Care to elaborate?

@davedelong
Copy link
Author

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.

@mattbischoff
Copy link
Contributor

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

eliperkins pushed a commit to venmo/objective-c-style-guide that referenced this issue Jan 20, 2015
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
Projects
None yet
Development

Successfully merging a pull request may close this issue.

3 participants