標籤:objective-c xcode ios 類 對象 物件導向
是一種半自動的記憶體管理方式
autorealease方法:
- (instancetype)autorelease
此方法將對象放到自動釋放池中,當自動釋放池銷毀時,池中的所有對象都會隨之銷毀。
常見的使用方式:
Person *p = [[[Perosn alloc] init] autorelease];
使用@autoreleasepool關鍵字來使用自動釋放池
其後的{…}相當於自動釋放池的生存期 ,如:
@autoreleasepool { Person *p = [[[Perosn alloc] init] autorelease]; …}
好處:不用關心對象釋放的時間、不用關心什麼時候調用release
注意:
1)佔用記憶體較大的對象盡量不要隨意使用autorelease
2) @autoreleasepool可以嵌套
系統中有一個自動釋放池的棧結構,autorelease方法是將對象放入到棧頂得池子中
3)不要多次調用autorelease,如:
[[[[Person alloc] init] autorelease] autorelease];
4)自動釋放池銷毀時會對池子中的對象release一次,也就是說autorelease方法並沒有更改引用計數。
將autorelease方法封裝在類對象方法中是一個比較好的做法
+ (AMPerson*) person { //return [[[Person alloc] init] autorelease]; return [[[self alloc] init] autorelease];}
舊版本的自動釋放池的使用:
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; …[pool release];
自Xcode5之後基本都是使用autorelease
本文出自 “teacherAn” 部落格,請務必保留此出處http://annmeng.blog.51cto.com/3321237/1745689
Objective-C(8)記憶體管理之自動釋放池