There are many examples of setter how we should do it, for example:
- (void)setFoo:(NSString *)newFoo
{
if (foo != newFoo)
{
[foo release];//??
foo = [newFoo retain];
}
}
I’m understanding that we need to release prev value and then assign new one with retain, that’s how documentation say us to do, but I can’t understand for what we should release, if assigning foo = [newFoo retain]; will make foo just a new value with newFoo’s current retain counter, and if even foo’s retain counter was 5 before, it will become newFoo’s + 1, or I something miss and understand incorrect. Why we can’t just do:
- (void)setFoo:(NSString *)newFoo
{
if (foo != newFoo)
{
foo = [newFoo retain];
}
}
Objective-C works with pointers (everything is a pointer).
When you perform
retainorreleaseyou are not doing that on the reference/pointer (your variable name) but on the actual object itself.That is why we need to release the old object (because we have finished with it), and point our variable to the new one, (then increase its
retaincount, so it doesn’t get removed by something else).Hope that makes sense