Reputation: 815
I'm a bit confused about the memory management examples regarding setters floating around various tutorials, articles, books, etc. Here is a typical variant:
- (void) setOldAmount: (NSNumber*)newAmount
{
if (oldAmount != newAmount) {
[oldAmount release];
oldAmount = [newAmount retain];
}
}
- (void) dealloc
{
[oldAmount release];
[super dealloc];
}
With oldAmount = [newAmount retain];
oldAmount's -retain message, is balanced by the -release message in -dealloc; but if newAmount is being sent the -retain and then assigned to oldAmount, where is newAmount released? Isn't this a memory leak?
Upvotes: 0
Views: 225
Reputation: 124997
newAmount and oldAmount are both pointers to objects. You retain and release objects via pointers, but it's the object that keeps track of how many times it has been retained. Two variables that point to the same object can be used interchangeably. For example:
NSNumber *a = [[NSNumber alloc] initWithInt:5];
NSNumber *b = a;
[b release];
The release on the third line balances the alloc on the first line because a and b both point to the same object.
It's the same in your example. newAmount is retained, but oldAmount is assigned to point to the same object. The next time -setOldAmount: (or -dealloc) is called, that object will be released. Note that:
oldAmount = [newAmount retain];
is just a bit of shorthand that means the same thing as:
oldAmount = newAmount;
[oldAmount retain];
except that the retain and assignment happen in a different order (which doesn't make any difference in the outcome).
It's good to understand what's happening in this code, but if you use properties with synthesized accessors you won't have to write it very often.
Upvotes: 2
Reputation: 121
You have to think of iPhone memory management in terms of ownership. If you take ownership of a variable, you need to "retain" it. If you retain an object, you need to release it. So the piece of code you can't see is the person calling setOldAmount. Whoever is calling setOldAmount most likely created newAmount. When you allocate a variable, it's implicitly set to be retained before given to you (otherwise it would be released before it got to you which would be silly). It's your job to release it when you don't care about it's value anymore. So yes, there could be a memory leak if whoever called setOldAmount never released newAmount, but the code above is correct.
Upvotes: 0