第六讲:Obj-C 内存管理4 - 自动释放池
轉:http://tigercat1977.blog.163.com/blog/static/2141561122012111294616203/
第六講:Obj-C 內存管理4 - 自動釋放池?
主要內容????? 什么是自動釋放池
????? 自動釋放池的好處
????? 如何創建一個自動釋放池
????? 自動釋放池如何釋放對象內存
????? 自動釋放池棧式結構管理
Autorelease pool
???? 1. 自動釋放池(Autorelease Pool)是 OC 的一種內存自動回收機制,可以將一些臨時變量通過自動釋放吃來回收統一釋放
???? 2. 當自動釋放池本身銷毀的時候,池子里所有的對象都會做一次 release 操作
autorelease
????? 任何OC對象只要調用 autorelease 方法,就會把該對象放大離自己最近的自動釋放池中(棧頂的釋放池)
創建自動釋放池 (兩種方法)
?????? IOS5.0 新方式
???? @ autoreleasepool
????? {
????? }
????? IOS5.0 之前的老方式
????? NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
????? [pool release];
遛狗原理
典型例子(正確)
????? Dog *dog1 = [[Dog alloc] init];
????? [xiaoLi setDog:dog1];
???? [dog1 release];
典型例子 (錯誤)
????? [xiaoLi setDog:[[Dog alloc] init]];
????? 上述代碼有內存泄漏
典型例子(正確)好的方法
???? Dog *dog = [[[Dog alloc] init] autorelease];
????? [xiaoLi setDog:dog1];
????? //這里不能跟 [dog1 release];
典型例子(正確) 放成一行
????? [xiaoLi setDog:[[[Dog alloc] init] autorelease]];
黃金法則
????? 如果對一個對象使用了 alloc, [mutable]copy, retain,那么必須使用相應的 release 或者 autorelease
舉例
// Dog.h #import <Foundation/Foundation.h> @interface Dog : NSObject { int _ID; } @property int ID; @end
// Dog.m #import "Dog.h" @implementation Dog @synthesize ID = _ID; - (void) dealloc { NSLog(@"dog %d dealloc", _ID); [super dealloc]; } @end
// Person.h #import <Foundation/Foundation.h> #import "Dog.h" @interface Person : NSObject { Dog *_dog; } @property (retain) Dog *dog; @end
// Person.m #import "Person.h" @implementation Person @synthesize dog = _dog; - (void) dealloc { self.dog = nil; NSLog(@"person dealloc"); [super dealloc]; } @end
// main.m #import <Foundation/Foundation.h> #import "Person.h" #import "Dog.h" int main (int argc, const char * argv[]) { NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; NSLog(@"Hello, World!"); Person *xiaoLi = [[Person alloc] init]; Dog *dog1 = [[[Dog alloc] init] autorelease]; // 把 dog1 這條狗放在自動釋放池里,上邊的pool中 NSLog(@"dog1 retaincount is %ld", [dog1 retainCount]); xiaoLi.dog = dog1; NSLog(@"dog1 retaincount2 is %ld", [dog1 retainCount]); // [dog1 release]; // autorelease 了,不需要再 release [xiaoLi release]; NSLog(@"dog1 retaincount3 is %ld", [dog1 retainCount]); [pool release]; NSLog(@"end of release"); return 0; } /* 輸出結果 Hello, World! dog1 retaincount is 1 dog1 retaincount2 is 2 person dealloc dog1 retaincount3 is 1 dog 0 dealloc end of release */
?
?
轉載于:https://www.cnblogs.com/jackljf/archive/2013/03/07/3589250.html
總結
以上是生活随笔為你收集整理的第六讲:Obj-C 内存管理4 - 自动释放池的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 将js文件打包进dll 方法3
- 下一篇: 各类编程语言视频教程(300G)