Don’t Use Accessor Methods in Initializer Methods and dealloc
Don’t Use Accessor Methods in Initializer Methods and dealloc
The only places you shouldn’t use accessor methods to set an instance variable are ininitializer methods anddealloc . To initialize a counter object with a number object representing zero, you might implement aninit method as follows:
- init {
self = [super init];
if (self) {
_count = [[NSNumber alloc] initWithInteger:0];
}
return self;
}
To allow a counter to be initialized with a count other than zero, you might implement aninitWithCount: method as follows:
- initWithCount:(NSNumber *)startingCount {
self = [super init];
if (self) {
_count = [startingCount copy];
}
return self;
}
Since the Counter class has an object instance variable, you must also implement adealloc method. It should relinquish ownership of any instance variables by sending them arelease message, and ultimately it should invoke super’s implementation: