I have already heard from several sources (stackoverflow.com, cocoa -dev, documentation, blogs, etc.) that it is "wrong" to use accessors and settings (foo, setFoo :) in your init and dealloc. I understand that there is a remote possibility to confuse other objects that observe the property if you do. (a simple example is given here below)
However, I must say that I disagree with this practice for the following reason:
The new Objective-C environment (one on the iPhone and the 64-bit runtime in 10.5) allows you to declare properties without declaring the corresponding ivar. For example, the following class will compile just fine on 10.5 or for the iPhone (device, not simulator):
@interface Foo : NSObject { } @property (retain) id someObject; @end @implementation Foo @synthesize someObject; @end
Understanding that the above is a perfectly valid Objective-C class, let's say I decided to write an initializer, and for the purposes of memory management, the dealloc method (since GC is not available on iPhone). All I have ever read about initializers and release would make me write the following two methods:
- (id) init { if (self = [super init]) { //initialize the value of someObject to nil [self setSomeObject:nil]; } return self; } - (void) dealloc { //setting someObject to nil will release the previous value [self setSomeObject:nil]; [super dealloc]; }
However, according to the documentation and popular opinion, this is "wrong." So my questions are these:
- How can I initialize someObject without using access? You could say that the compiler (or the runtime or something else) guarantees that someObject is already set to zero, but I believe that it would be wrong behavior to rely on this. Having a decent background in C, I saw a lot of errors due to incorrect variable initialization, and this seems a bit different.
- How can I free someObject if I should not use accessor in the dealloc method?
If the answer to any of them is “you cannot,” then how bad will it be to use accessors in your init and dealloc methods?
initialization properties objective-c accessor dealloc
Dave DeLong Aug 16 '09 at 4:08 2009-08-16 04:08
source share