3. Memory Management - Overview
Memory Management is the process of allocating and
managing memory during programs life cycle.
3
4. Basic Memory Management Rules
• You own a object when you create it using “new”, “alloc”, “copy” or “mutableCopy”.
• Any object may have one or more owners
• Object creator will be the first owner while others can own the objects using
Object Ownership “retain”.
• Owners are responsible to release the objects
• If any object does not have any owner, it will be release by system.
• Autorelease method is used to automatically release the memory.
• Autorelease “defer” releasing object.
• Every thread should have it’s own memory pool.
Auto Release
• New objects are created with reference count = 1
• Retain/Release increase/decrease reference count of the object
• When reference count = 0, object is release automatically.
Reference Count
4
5. Examples
Creating object:
Employee* emp= [[Employee alloc] init];
// alloc will increase reference count to
1
Using object:
[emp setName:@”James”];
[emp setPhone:4081120239];
Releasing object:
[emp release];// emp is invalid now Ref
Count = 0
Emp = nil; // Best practice
5
6. Properties
Use Accessor methods to make memory management
easier.
@propery (atomicity, writability, setter) type name;
@synthesize name= varName;
Usage:
object.propertyName = newValue;
value = object.propertyName;
When we declare -
@property (nonatomic, retain) NSString* name;
// Above statement is equivalent to
-(NSString*)name {
return name;
}
-(void)setName:(NSString*)aName {
if (name != aName)
{
[name release];
name = [aName retain];
}
}
6
8. Best Practices
• Explicitly release ownership after object is done.
• Release early if you are done, avoid using
autorelease.
• Use Instrument, Static Analysis tools.
• Don’t ignore compiler warnings.
• Do Unit testing.
8