main.m
#import <Foundation/Foundation.h>
#import "Person.h"
int main(int argc, const char * argv[]) {
/*
Person *p = [[Person alloc] init];
@autoreleasepool {
// Person *p = [[[Person alloc] init] autorelease];
// [p run];
// 2.在自動釋放池中創(chuàng)建了對象, 一定要調(diào)用autorelease,才會將對象放入自動釋放池中
// Person *p = [[Person alloc] init];
// [p run];
// 3.只要在自動釋放池中調(diào)用autorelease, 就會將對象放入自動釋放池
p = [p autorelease];
[p run];
}
// 1.一定要在自動釋放池中調(diào)用autorelease, 才會將對象放入自動釋放池中
// Person *p = [[[Person alloc] init] autorelease];
*/
/*
// 4.一個程序中可以創(chuàng)建N個自動釋放池, 并且自動釋放池還可以嵌套
// 如果存在多個自動釋放池的時候, 自動釋放池是以 "棧" 的形式存儲的
// 棧的特點: 先進后出
// 給一個對象方法發(fā)送一條autorelease消息, 永遠會將對象放到棧頂?shù)淖詣俞尫懦?@autoreleasepool { // 創(chuàng)建第一個釋放池
@autoreleasepool { // 創(chuàng)建第二個釋放池
@autoreleasepool { // 創(chuàng)建第三個釋放池
Person *p = [[[Person alloc] init] autorelease];
[p run];
} // 第三個釋放池銷毀
Person *p = [[[Person alloc] init] autorelease];
}// 第二個釋放池銷毀
}// 第一個釋放池銷毀
*/
@autoreleasepool {
// 千萬不要寫多次autorelease
// 一個alloc, new對應(yīng)一個autorelease
// Person *p = [[[[Person alloc] init] autorelease] autorelease];
// 如果寫了autorelease就不要寫release
// 總之記住: 一個alloc/new對應(yīng)一個autorelease或者release
Person *p = [[[Person alloc] init] autorelease];
[p release];
}
return 0;
}
"ViewController.m
#import "ViewController.h"
#import "Person.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
/*
// 1.不要再自動釋放池中使用比較消耗內(nèi)存的對象, 占用內(nèi)存比較大的對象
@autoreleasepool {
Person *p = [[[Person alloc] init] autorelease];
// 假如p對象只在100行的地方使用, 以后都不用了
// 一萬行代碼
}
*/
// 2.盡量不要再自動釋放池中使用循環(huán), 特別是循環(huán)的次數(shù)非常多, 并且還非常占用內(nèi)存
@autoreleasepool {
for (int i = 0; i < 99999; ++i) {
// 每調(diào)用一次都會創(chuàng)建一個新的對象
// 每個對象都會占用一塊存儲空間
Person *p = [[[Person alloc] init] autorelease];
}
} // 只有執(zhí)行到這一行, 所有的對象才會被釋放
/*如果使用循環(huán)這樣寫比較好一點
for (int i = 0; i < 99999; ++i) {
@autoreleasepool {
Person *p = [[[Person alloc] init] autorelease];
} // 執(zhí)行到這一行, 自動釋放池就釋放了
}
*/
NSLog(@"--------");
}
@end
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。