I\'ve heard now from several sources (stackoverflow.com, cocoa-dev, the documentation, blogs, etc) that it is \"wrong\" to use accessors and settings (foo, setFoo:) in your
EDIT (Feb 13, 2013): As noted in my comment below, and especially since the addition of ARC, I've changed my mind on this. Prior to ARC, I saw a lot of crash-causing bugs due to incorrect ivar assignments in init
. IMO, especially working with junior teams, the rare problems with using accessors in init
were outweighed by the common bugs of ivar access. Since ARC has eliminated these kinds of bugs, the rare-but-possible bugs that using accessor in init
can cause are more important, and so I've switched to supporting the direct use of ivars in init
and dealloc
, and only in those places; accessors everywhere else that is possible (obviously you can't use accessors inside of the accessor itself....)
PRE-ARC answer
I strongly disagree with those who object to accessors in -init
. In almost all cases this is a very good place to use accessors, and it saves a lot of bugs I've seen in new Cocoa coders who invariably fail to retain when assigning in -init
.
-dealloc
is a tougher call. I have a natural inclination to use accessors there (so that they are used everywhere), but it can cause headaches due to KVO (or even NSNotifications if you post a change notification in your setter). That said, while I don't use accessors in -dealloc
, I consider it very debatable and Apple is very inconsistent about it (we know they're calling setView:
in UIViewController's -dealloc
for instance).
In any case, I would say that under-use of accessors has caused 100x the bugs of over-use. I would always err towards using them except when there is a strong reason not to.
I understand that the current 10.5 behavior under which the synthesized ivars are not directly accessible is considered by Apple to be a bug; you should be able to directly access it, but can't.
Hence, you should be able to do:
someObject = nil;
instead of
self.someObject = nil;
In the meantime, using the accessor directly is the only way to do it without providing an explicit ivar.
Update: This bug has been fixed; you can now do someObject = nil
just fine.