美文网首页iOS自我学习库iOS 进阶
weakSelf和strongSelf的宏定义

weakSelf和strongSelf的宏定义

作者: 小朴同学 | 来源:发表于2017-10-19 20:42 被阅读250次

弱引用与强引用

__weak typeof(type) 与 __strong typeof(type)。
typeof()可以根据括号里面的变量,自动识别变量类型并返回该类型。__weak弱引用,__strong强引用

  1. 使用的方式
    • 默认使用方式
    __weak __typeof__(self) weakSelf = self;
    __strong __typeof__(weakSelf) strongSelf = weakSelf;
    
    • 宏定义使用
    1. 使用@WeakSelf的方式,这种方式用法有点像原生使用(个人感觉略微装逼的使用方式,但是用着不爽,代码不主动补全(可以拉成代码块,然后就好了))
    #define WeakSelf(type) autoreleasepool{} __weak __typeof__(type) weakSelf = type;
    #define StrongSelf(type) autoreleasepool{} __strong __typeof__(type) strongSelf = type;
    
    // 如此定义之后可以在这句代码之后直接使用变量weakSelf
    @WeakSelf(self);
    weakSelf.title = @"下一个界面"; // 例如如此使用
    // 强引用也是如此
    @StrongSelf(weakSelf); // 这里是weakSelf
    strongSelf.title = @"下一个界面";
    
    2. 使用WeakSelf
    #define WeakSelf(type) __weak __typeof__(type) weakSelf = type;
    #define StrongSelf(type) __strong __typeof__(type) strongSelf = type;
    // 如此定义之后可以在这句代码之后直接使用变量weakSelf
    WeakSelf(self);
    weakSelf.title = @"下一个界面"; // 例如如此使用
    // 强引用也是如此
    StrongSelf(weakSelf); // **这里是weakSelf**
    strongSelf.title = @"下一个界面";
    
    • 另一个宏定义的方式
    #define selfWeak(type) autoreleasepool{} __weak typeof(type) type##Weak = type;
    #define selfStrong(type) autoreleasepool{} __strong typeof(type##Weak) type##Strong = type##Weak;
    或者
    #define selfWeak(type) __weak typeof(type) type##Weak = type;
    #define selfStrong(type) __strong typeof(type##Weak) type##Strong = type##Weak;
    
    这是对第一种的扩展,可以适应更多的方式。我使用selfWeak,只是想保持第二个变量大写。
    当然你也可以使用这种方式
    #define WeakSelf(type) __weak typeof(type) weak##type = type;
    #define StrongSelf(type) __strong typeof(weak##type) strong##type = weak##type;
    
    // 如此定义之后可以在这句代码之后直接使用变量weakself
    WeakSelf(self);
    weakself.title = @"下一个界面"; // 例如如此使用
    // 强引用也是如此
    StrongSelf(self); // **这里是self**
    strongself.title = @"下一个界面";
    
    • 区别一就是第一个只适用与self,另一个使用面广。
    • 区别二用法上,第一个StrongSelf(weakSelf),另一个StrongSelf(self)。就是第二个会自动处理变量名字。

参考资料
iOS——Block等词的小解释
进阶知识: iOS 底层解析weak的实现原理

相关文章

网友评论

    本文标题:weakSelf和strongSelf的宏定义

    本文链接:https://www.haomeiwen.com/subject/tuppuxtx.html