标签:
1. 谁 alloc ,谁 release;
2. 谁要占用谁retain;
3. 谁不想占用对象时就 让对象计数器release;
4.谁 retain,谁release;
1 // Book类 2 @interface Book:NSObject 3 4 { 5 6 int _price; // 书的价格 7 8 } 9 // Book的 get set方法 10 - (void)setPrice:(int) price; 11 12 - (int)price; 13 14 @end 15 16 @implementation Book 17 - (void)setPrice:(int) price{ 18 19 _price = price; 20 } 21 22 - (int)price{ 23 return _price; 24 } 25 26 - (void)dealloc{ 27 28 NSLog(@"Book对象被回收"); 29 [super dealloc]; 30 31 } 32 @end 33 34 35 // Person类的声明与实现 Person.h 36 37 @interface Person:NSObject 38 { 39 Book *_book; 40 41 } 42 // get set方法声明 43 - (void)setBook:(Book *) book; 44 - (Book *)book; 45 46 @end 47 48 // Person.m 49 50 @implementation Person 51 52 - (void)setBook:(Book *) book{ 53 54 _book = [book retain]; //计数器+1 55 } 56 57 - (Book *)book{ 58 return _book; 59 } 60 61 // 重写 dealloc 62 - (void)dealloc{ 63 [_book release]; 64 NSLog(@"person对象被回收"); 65 [super dealloc] ;// 最后写super dealloc 66 } 67 @end 68 69 70 71 72 73 74 75 int main(){ 76 77 Person *p = [ [Person alloc] init ]; // p 计数器 +1 78 Book *b = [ [Book alloc] init ]; // b 计数器 +1 79 [ p setBook:b]; // 使用Book 时 retain; b计数器值2 80 81 82 [b release]; // 计数器 2 -1 =1 83 84 [p release];// p计数器为0调用 Person 的dealloc 对Book release 85 b = nil; 86 p = nil; 87 88 return 0 ; 89 90 }
标签:
原文地址:http://www.cnblogs.com/jerry1209/p/4243097.html