2009年2月9日 星期一

memory management

use retain count to do memory management

when retain count becomes 0, the object is destroyed(is sent dealloc message)

when object is created via alloc, new, or copy, the object's retain count is set to 1

use retain to increase retain count

use release to decrease retain count

use retainCount to know object's retain count

retain count in accessor:
ex:
class Boy has an instance variable for book
- (void) setBook: (Book*) newBook
{
[newBook retain];
[book release];
book = newBook;
}
note:
when boy object is deallocated, it will release book object's retain count for retain count it increase in setBook

autorelease:
when object is sent autorelease message, it is put in autorelease pool
when the pool is destroyed, all objects in pool are sent a release message
ex:
NSAutoreleasePool *pool;
pool = [[NSAutoreleasePool alloc] init];
Book *book = [[Book alloc] init];
[book autorelease];
[pool release];
note:
1. for iphone, avoid using autorelease and the functions that give autoreleased object
2. the same object can be autoreleased many times

drain:
the drain method for pool empties out the pool without destroying the pool

rule for reatin count:
1. when getting object from new, alloc, or copy, you must send the object release or autorelease when you are done with it
2. when getting object via other methods, assume it has a retain count of 1 and it has been autoreleased . If you want to hold object for some time, just retain it and release it when you are done
ex:
in an event loop, a pool is created before handling event. And the pool is destroyed after handling event. Hence, the object created during the event loop must retain if you want to keep it
3. if your retain an object, you need to release or autorelease it

garbage collection:
not support iphone
enable gc:
Build -> objective-c garbage collection

沒有留言:

張貼留言