美文网首页
解决Block中顽疾的几种配方

解决Block中顽疾的几种配方

作者: 小鲲鹏 | 来源:发表于2019-04-17 11:19 被阅读0次

    第一种:常见常用的配方 

    为了数据的安全,在弱引用的同时,在里面一定要使用strong去强引用,否则会导致数据的丢失。即输出的name为null。

    强弱共舞配方

    解释:

    __strong typeof(self) strongSelf = weakSelf    与   __strong typeof(weakSelf) strongSelf = weakSelf

    typeof is not a function, it's a keyword and isn't used at runtime at all. All __strong typeof(self) is doing here is telling the compiler how to evaluate the symbol strongSelf. It doesn't cause any runtime code to be generated, because it doesn't matter at runtime what that type actually is. All those decisions are made at compile-time

    参考链接:typeof关键词

    第二种:__block 配方      self->block ->vc->self  循环引用

    注意点:如果该block没有被调用,意味着循环引用没有打破。所以__block 修饰的vc被block持有,则该block必须被调用。

    __block配方

    第三种: 传参配方    把self当做参数的形式传入

    传参配方


    总结:推荐第三种配方

    1.第三种配方相比第一种和第二种代码量上少了很多,而且数据相对安全。

    2.第三种配方相比第二种不存在不调用,不能释放的问题。

    3.第三种在编译和解析的时候最简单,性能最优的。

    相关文章

      网友评论

          本文标题:解决Block中顽疾的几种配方

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