f(sixleaves) = sixleaves

重剑无锋 大巧不工

  C++博客 :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理 ::
  95 随笔 :: 0 文章 :: 7 评论 :: 0 Trackbacks
main.m
 1 //
 2 //  main.m
 3 //  循环引用与循环retain
 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 "Card.h"
12 
13 
14 
15 // 重点介绍循环retain,循环引用比较好理解
16 /*
17  循环引用:
18  当两个类的头文件中都使用#import或者#include包含对方,就会照成循环引用。而会引发
19  编译错误。如果是前者,则由于#import虽然不会导致死循环,例如:A、B两个头文件相互
20  import,假设A先编译好了,但到了B,因为B在A中已经import,你在B中import A时候,又
21  把B import进来,但是B无法被import到自身,会导致其中一个无法被正常编译。而后
22  #include就如同一个死循环,所以也会出错。
23  
24  总结:
25  @class的2点作用
26  1.用来在头文件中前置声明要用到的类,而不用导入头文件,减少了要引用的文件,提高编译效率。
27  2.用来解决循环引用导致编译时出错。
28  */
29 
30 int main(int argc, const char * argv[]) {
31     
32     Person *p = [[Person alloc] init];
33     
34     Card *c = [[Card alloc] init];
35     
36     // 相互retain、造成类似死锁问题,导致两个对象都不能被释放。
37     // 解决办法,破坏环。
38     // 如何破坏环呢,那么势必有一个类中不能在使用retain
39     // 也就是说一个使用retain、一个使用assign就能够成功解决这个问题。
40     p.card = c;
41     c.person = p;
42     
43     [c release];
44     [p release];
45 
46     return 0;
47 }
48 


Person.h
 1 //
 2 //  Person.h
 3 //  循环引用与循环retain
 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 
11 @class Card;
12 
13 @interface Person : NSObject
14 
15 @property (nonatomic, retain) Card *card;
16 
17 @end
18 
Person.m

 1 
 2 //
 3 //  Person.m
 4 //  循环引用与循环retain
 5 //
 6 //  Created by sixleaves on 15/5/9.
 7 //  Copyright (c) 2015年 itcast. All rights reserved.
 8 //
 9 
10 #import "Person.h"
11 #import "Card.h"
12 @implementation Person
13 
14 - (void)dealloc
15 {
16     [_card release];
17     [super dealloc];
18 }
19 
20 @end
21 
Card.h
 1 //
 2 //  Card.h
 3 //  循环引用与循环retain
 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 
11 @class Person;
12 
13 @interface Card : NSObject
14 
15 // 破坏环
16 @property (nonatomic, assign) Person *person;
17 
18 @end
19 
Card.m
 1 //
 2 //  Card.m
 3 //  循环引用与循环retain
 4 //
 5 //  Created by sixleaves on 15/5/9.
 6 //  Copyright (c) 2015年 itcast. All rights reserved.
 7 //
 8 
 9 #import "Card.h"
10 #import "Person.h"
11 @implementation Card
12 
13 - (void)dealloc
14 {
15     // 破坏环后,这边就不用再release了。
16     //[_person release];
17     
18     [super dealloc];
19 }
20 
21 @end
22 
posted on 2015-05-09 16:56 swp 阅读(211) 评论(0)  编辑 收藏 引用 所属分类: objective-c

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