iOS 代理为啥要用weak修饰?
2024-09-06 19:11:23
在开发中我们经常使用代理,或自己写个代理,而代理属性都用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不会。
最新文章
- MySql分页算法
- 洛谷 P1204 [USACO1.2]挤牛奶Milking Cows Label:模拟Ex 74分待查
- UE4 WCF RestFul 服务器 读取JSON 数据并解析 简单实例
- poj 1195:Mobile phones(二维树状数组,矩阵求和)
- Orchard Compact v1.7.2
- tableView在加载数据成功之前先展示了footerView-医生工作台1期
- openldap 安装 配置 使用
- Android之TextureView浅析
- adb server didn t ack failed to start daemon
- BOM数据基础 - Mobox物料编码管理及实现
- C#操作MongoDB的简单实例
- 关于html中图片上传预览的实现
- Jvm垃圾回收器(终结篇)
- NPOI 读取excel的时候,时间格式的处理
- bzoj 3277
- 【splunk】按时间统计并找到异常值
- word之个人设置
- f5单台安装配置
- unigui web app之菜单
- JetBrains PhpStorm 2017.2 x64 激活