在开发中我们经常使用代理,或自己写个代理,而代理属性都用weak(assign)修饰,看过有些开发者用strong(retain),但并没发现有何不妥,也不清楚weak(assign)与strong(retain)修饰有何区别

功能实现就行了,考虑这么多干嘛~~~我只能哈哈哈

  • weak:指明该对象并不负责保持delegate这个对象,delegate这个对象的销毁由外部控制
@property (nonatomic, weak) id<HSDogDelegate>delegate;
  • strong该对象强引用delegate,外界不能销毁delegate对象,会导致循环引用(Retain Cycles)
@property (nonatomic, strong) id<HSDogDelegate>delegate;

可能你还不太理解,没关系,下面先举例,看结果,再分析!

举例

  • HSDog类
    HSDog.h: @protocol HSDogDelegate <NSObject>
    @end @interface HSDog : NSObject @property (nonatomic, weak) id<HSDogDelegate>delegate; @end
    HSDog.m: #import "HSDog.h" @implementation HSDog - (void)dealloc
    {
    NSLog(@"HSDog----销毁");
    } @end
    HSPerson类
    HSPerson.h: @interface HSPerson : NSObject @end
    HSPerson.m: #import "HSPerson.h"
    #import "HSDog.h" @interface HSPerson()<HSDogDelegate>
    /** 强引用dog*/
    @property (nonatomic, strong) HSDog *dog;
    @end @implementation HSPerson - (instancetype)init
    {
    self = [super init];
    if (self) {
    // 实例化dog
    self.dog = [[HSDog alloc] init];
    // dog的delegate引用self,self的retainCount,取决于delegate修饰,weak:retainCount不变,strong:retainCount + 1
    self.dog.delegate = self; }
    return self;
    } - (void)dealloc
    {
    NSLog(@"HSPerson----销毁");
    } @end
    在ViewController实现:
    #import "ViewController.h"
    #import "HSPerson.h" @interface ViewController ()
    @end @implementation ViewController
    - (void)viewDidLoad {
    [super viewDidLoad];
    // 实例化person, self对person弱引用,person的retainCount不变
    HSPerson *person = [[HSPerson alloc] init]; }
    @end

结果

  • weak修饰代理
@property (nonatomic, weak) id<HSDogDelegate>delegate;

运行->打印

HSPerson----销毁
HSDog----销毁
  • strong修饰代理
@property (nonatomic, strong) id<HSDogDelegate>delegate;

运行->打印
....并未打印,说明HSPerson、HSDog对象没调用dealloc方法,两个对象未销毁
这也是我们经常说的内存泄露,该释放的内存并未释放!

附:

我们知道苹果在代理上给我们使用了weak和assign来修饰,但是两者有什么不同呢,那是因为weak可以将代理对象置为nil,而assgin不会。

最新文章

  1. MySql分页算法
  2. 洛谷 P1204 [USACO1.2]挤牛奶Milking Cows Label:模拟Ex 74分待查
  3. UE4 WCF RestFul 服务器 读取JSON 数据并解析 简单实例
  4. poj 1195:Mobile phones(二维树状数组,矩阵求和)
  5. Orchard Compact v1.7.2
  6. tableView在加载数据成功之前先展示了footerView-医生工作台1期
  7. openldap 安装 配置 使用
  8. Android之TextureView浅析
  9. adb server didn t ack failed to start daemon
  10. BOM数据基础 - Mobox物料编码管理及实现
  11. C#操作MongoDB的简单实例
  12. 关于html中图片上传预览的实现
  13. Jvm垃圾回收器(终结篇)
  14. NPOI 读取excel的时候,时间格式的处理
  15. bzoj 3277
  16. 【splunk】按时间统计并找到异常值
  17. word之个人设置
  18. f5单台安装配置
  19. unigui web app之菜单
  20. JetBrains PhpStorm 2017.2 x64 激活

热门文章

  1. java算法面试题:递归算法题1
  2. c++引用与指针的区别
  3. C++的新特性for-each
  4. Linux下重要日志及查看方式
  5. 第八篇:ORM框架SQLAlchemy 了解知识
  6. JZOJ 3509. 【NOIP2013模拟11.5B组】倒霉的小C
  7. HDU_6194 后缀数组+RMQ
  8. 异步消息处理机制,UI更新
  9. java并发面试题-基础
  10. spoj 104 Highways(Matrix-tree定理)