1.autorelease的基本用法
1> 會將對象放到一個自動釋放池中
2> 當自動釋放池被銷燬時,會對池子裏面的所有對象做一次release操作
3> 會返回對象本身
4> 調用完autorelease方法後,對象的計數器不變
2.autorelease的好處
1> 不用再關心對象釋放的時間
2> 不用再關心什麼時候調用release
3.autorelease的使用注意
1> 佔用內存較大的對象不要隨便使用autorelease
2> 佔用內存較小的對象使用autorelease,沒有太大影響
4.錯誤寫法
1> alloc之後調用了autorelease,又調用release
@autoreleasepool
{
// 1
Person *p = [[[Person alloc] init] autorelease];
// 0
[p release];
}
2> 連續調用多次autorelease
@autoreleasepool
{
Person *p = [[[[Person alloc] init] autorelease] autorelease];
}
5.自動釋放池
1> 在iOS程序運行過程中,會創建無數個池子。這些池子都是以棧結構存在(先進後出)
2> 當一個對象調用autorelease方法時,會將這個對象放到棧頂的釋放池
6.自動釋放池的創建方式
1> iOS 5.0前
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
[pool release]; // [pool drain];
2> iOS 5.0 開始
@autoreleasepool
{
}
Person.h
#import <Foundation/Foundation.h>
@interface Person : NSObject
@property (nonatomic, assign) int age;
@end
Person.h
#import "Person.h"
@implementation Person
- (void)dealloc
{
NSLog(@"Person---dealloc");
[super dealloc];
}
@end
main函數
#import <Foundation/Foundation.h>
#import "Person.h"
int main()
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
Person *pp = [[[Person alloc] init] autorelease];
[pool release]; // [pool drain];
@autoreleasepool
{
// 1
Person *p = [[[[Person alloc] init] autorelease] autorelease];
// 0
// [p release];
}
return 0;
}
void test()
{
@autoreleasepool
{// { 開始代表創建了釋放池
// autorelease方法會返回對象本身
// 調用完autorelease方法後,對象的計數器不變
// autorelease會將對象放到一個自動釋放池中
// 當自動釋放池被銷燬時,會對池子裏面的所有對象做一次release操作
Person *p = [[[Person alloc] init] autorelease];
p.age = 10;
@autoreleasepool
{
// 1
Person *p2 = [[[Person alloc] init] autorelease];
p2.age = 10;
}
Person *p3 = [[[Person alloc] init] autorelease];
} // } 結束代表銷燬釋放池
}