May 27, 2014

Fast food objective-c (part 7) : More on Memory Management

Objective-C's memory management system is called reference counting. All you have to do is keep track of your references, and the runtime does the actual freeing of memory. 
In simplest terms, you alloc an object, maybe retain it at some point, then send one release for each alloc/retain you sent. So if you used alloc once and then retain once, you need to release twice.
learnobjectivec-referencecounting



That's the theory of reference counting. But in practice, there are usually only two reasons to create an object: 
1. To keep it as an instance variable
2. To use temporarily for single use inside a function 
In most cases, the setter for an instance variable should just autorelease the old object, and retain the new one. You then just make sure to release it in dealloc as well. 
So the only real work is managing local references inside a function. And there's only one rule: if you create an object with alloc or copy, send it a release or autorelease message at the end of the function. If you create an object any other way, do nothing. 
Here's the first case, managing an instance variable:
- (void) setTotalAmount: (NSNumber*)input
{
    [totalAmount autorelease];
    totalAmount = [input retain];
}

- (void) dealloc
{
    [totalAmount release];
    [super dealloc];
}
Here's the other case, local references. We only need to release the object created with alloc:
NSNumber* value1 = [[NSNumber alloc] initWithFloat:8.75];
NSNumber* value2 = [NSNumber numberWithFloat:14.78];

// only release value1, not value2
[value1 release];
And here's a combo: using a local reference to set an object as an instance variable:
NSNumber* value1 = [[NSNumber alloc] initWithFloat:8.75];
[self setTotal:value1];

NSNumber* value2 = [NSNumber numberWithFloat:14.78];
[self setTotal:value2];

[value1 release];
Notice how the rules for managing local references are exactly the same, regardless of whether you're setting them as instance variables or not. You don't need to think about how the setters are implemented. 
If you understand this, you understand 90% of what you will ever need to know about Objective-C memory management.

No comments:

Post a Comment