基本用法;
1,autorelease 方法會返回對象本身
2,調用完autorelease方法后,對象的
計數器不變
2,autorelease 會將對象放到一個自動釋放池中
3,當自動釋放池被銷毀時,會對池子里面的所有對象做一次release操作
autorelease的好處:
1》不用再關心對象釋放的時間
2》不用再關心什么時候調用release
autorelease的使用注意:
1》占用內存較大的對象不要隨便使用autorelease;
2>占用用內存較小的對象使用autorelease,沒有太大的影響
錯誤寫法:
1》alloc之后調用了autorelease,又調用了release
@autoreleasepool
{
Person * p = [ [ [Person alloc] init] autorelease]
[ p release];
}
2》連續調用多次autorelease
@autoreleasepool
{
Person * p =[ [ [ [Person alloc] init] autorelease] release]
}
自動釋放池:
1》在IOS程序運行過程中,會創建無數個池子,這些池子都是以棧結構存在(先進后出)
2》當一個對象調用autorelease方法時,會將這個對象放到棧頂的釋放池
自動釋放池的創建方式:
1》IOS5.0之前:
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
[pool release] ; // [pool drain];
2>IOS5.0開始
}
1,系統自帶的方法里沒有包含alloc, new , copy,說明返回的對象都是autorelease,如NSString * s = @"adaf";
2,開發中經常回提供一些類方法,快速創建一個已經autorelease過的對象
1》創建對象時不要直接用類名,一般用self
+(id) person
{
return [ [ [self alloc] init ] autorelease];
}
int main ( ) {
@autoreleasepool//必須加池子
{
Person * p =[ [ [Person alloc] init ] autorelease];
}
}
可以在創建類方法精簡Person的初始話:
+(id) person
{
return [ [ [Person alloc] init ] autorelease];
}