1 //
2 // main.m
3 // autorelease.m
4 //
5 // Created by sixleaves on 15/5/9.
6 // Copyright (c) 2015年 itcast. All rights reserved.
7 //
8
9 #import <Foundation/Foundation.h>
10 #import "Person.h"
11 #import "Dog.h"
12 int main(int argc, const char * argv[]) {
13 @autoreleasepool { // pool1入棧
14
15 // p-1
16 Person *p = [[[Person alloc] init] autorelease];
17 // c-1
18 Dog *c = [[[Dog alloc] init] autorelease];
19
20 // p -1 c-2
21 p.dog = c;
22
23
24 @autoreleasepool { // pool2入棧
25
26 // p1-1
27 Person *p1 = [[[Person alloc] init] autorelease];
28 // c1-1
29 Dog *c1 = [[[Dog alloc] init] autorelease];
30
31 // p1 -1 c-2
32 p1.dog = c1;
33
34
35 } // pool2出棧銷毀
36
37
38
39 } // pool1出棧銷毀。
40
41 return 0;
42 }
43 /*
44 自動(dòng)釋放池的管理是通過棧這個(gè)數(shù)據(jù)結(jié)構(gòu)進(jìn)行管理。
45
46 autorelease的優(yōu)點(diǎn):
47 1.不要在關(guān)心對(duì)象的釋放時(shí)間。
48 2.不用再關(guān)心什么時(shí)候用release。
49
50 autorelease的使用場(chǎng)合(注意點(diǎn)):
51 1.對(duì)于占用內(nèi)存交大的對(duì)象,不要使用autorelease,因?yàn)椴荒芫_的控制對(duì)象釋放的時(shí)間。
52 2.反之,對(duì)于占用內(nèi)存小的,使用autorelease的影響比較小。
53
54 autorelease添加到那個(gè)池子:
55 1.通過棧的結(jié)構(gòu),我們可以很容易的理解,autorelease是添加到當(dāng)前管理池子的棧
56 中棧頂?shù)贸刈印?br />57
58
59 autorelease的常見錯(cuò)誤(本質(zhì)都是最終會(huì)多次調(diào)用release):
60 1.連續(xù)調(diào)用autorelease。
61 2.在自動(dòng)釋放池中有效范圍中,同時(shí)條用了autorelease與release。
62
63
64 // 在啰嗦幾句:
65 // 在ios運(yùn)行中,系統(tǒng)會(huì)自動(dòng)創(chuàng)建很多的池子,所以autorelease作用在
66 // 的池子,是指棧頂?shù)某刈印?br />67 //
68 //
69
70 */
71