f(sixleaves) = sixleaves

重剑无锋 大巧不工

  C++博客 :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理 ::
  95 随笔 :: 0 文章 :: 7 评论 :: 0 Trackbacks
main.m
 1 //
 2 //  main.m
 3 //  set方法内存管理
 4 //
 5 //  Created by sixleaves on 15/5/8.
 6 //  Copyright (c) 2015年 itcast. All rights reserved.
 7 //
 8 
 9 #import <Foundation/Foundation.h>
10 #import "Person.h"
11 #import "Car.h"
12 int main(int argc, const char * argv[]) {
13     
14     // p1-1
15     Person *p1 = [[Person alloc] init];
16     // c1-1
17     Car *c1 = [[Car alloc] init];
18     c1.speed = 100;
19     
20     // c1-2
21     p1.car = c1;
22     
23     // c2-1
24     Car *c2 = [[Car alloc] init];
25     c2.speed = 200;
26     
27     // c1-1 c2-2
28     p1.car = c2; // 不想用时候就要release,再retain新对象。所以原车要先release,再retain新车
29     
30     // c2-1
31     [c2 release];
32     // c1-0
33     [c1 release];
34     //c2-0 p1-0
35     [p1 release];
36     return 0;
37 }
38 
39 /*
40  总结:
41  1.setter方法的代码规范:
42      基本数据类型:直接赋值
43      - (void)setAge:(int)age
44      {
45         _age =age;
46      }
47  
48      OC对象类型
49      - (void)setCar:(Car *)car
50      {
51         if ( car != _car) { // 1.先判断是不是传进来对象(避免让car成为僵尸对象)
52             
53             [_car release]; // 2.对旧对象做一次release
54             _car = [car retain];  // 3.对新对象做一次retain
55         }
56      }
57  
58  2.dealloc方法的代码规范
59     1.对当前对象所拥有的其他对象进行release。
60     2.调用父类的dealloc,并且放在最后。
61  
62  */
63 
Person.m
 1 //
 2 //  Person.m
 3 //  set方法内存管理
 4 //
 5 //  Created by sixleaves on 15/5/8.
 6 //  Copyright (c) 2015年 itcast. All rights reserved.
 7 //
 8 
 9 #import "Person.h"
10 #import "Car.h"
11 @implementation Person
12 - (void)setCar:(Car*)car
13 {
14     if ( car != _car) { // 1.先判断是不是新传进来的对象,免得如果当前
15                         // _car对象引用计数器为1,而car也指向当前对象
16                         // 时候,会引发野指针错误。
17         [_car release]; // 2.对旧的对象做一次release,因为不想用了
18         _car = [car retain]; // 3.对新对象做一次retain
19     }
20 }
21 - (Car *)car
22 {
23     return _car;
24 }
25 
26 - (void)dealloc
27 {
28     [_car release];
29     NSLog(@"Person-dealloc");
30     [super dealloc];
31 }
32 @end
33 
Car.m
 1 //
 2 //  Car.m
 3 //  set方法内存管理
 4 //
 5 //  Created by sixleaves on 15/5/8.
 6 //  Copyright (c) 2015年 itcast. All rights reserved.
 7 //
 8 
 9 #import "Car.h"
10 
11 @implementation Car
12 - (void)setSpeed:(int)speed
13 {
14     _speed = speed;
15 }
16 - (int)speed
17 {
18     return _speed;
19 }
20 
21 - (void)dealloc
22 {
23     
24     NSLog(@"speed = %d,Car-dealloc", _speed);
25     [super dealloc];
26 }
27 @end
28 
posted on 2015-05-08 15:07 swp 阅读(117) 评论(0)  编辑 收藏 引用 所属分类: objective-c

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理