iOS 不使用 Weak-Strong Dance,怎么避免循环

作者: 豪冷 | 来源:发表于2019-05-07 09:57 被阅读22次

    疑惑

    以下是引用:

    这是来自 PopCustomAnimation.h 
    
    /**
    
    @param target The object being animated.
    
    Reference the passed in target to help avoid retain loops.
    
    */
    
    typedef BOOL (^POPCustomAnimationBlock)(id target, POPCustomAnimation *animation);
    
    
    这个block里面的参数,从某种意义上来说,是冗余的。因为你从block中总是能够 显式的引用到任何的外部对象。
    
    但是它是非常有用的,因为现在你能够使用参数,而不是做一个 weak 的引用。
    

    之前看到这个的时候,一直没想明白
    直到后来看了这篇文章
    使用 Heap-Stack Dance 替代 Weak-Strong Dance,优雅避开循环引用
    的详细介绍后
    才明白


    正题

    之前有看到过
    iOS 之 UIControl 的 Block 响应方式
    这种使用方式
    缺点是需要使用 Weak-Strong Dance
    来避免循环引用

    于是
    我就想着
    既然明白了不使用 Weak-Strong Dance 就能避免循环引用的道理
    为何不改进一下 UIControl 的 Block 响应方式 呢?


    实现

    参考 BlocksKit 中 UIControl+BlocksKit.m的实现方式

    实现如下:

    .h

    typedef void(^JHUIControlBlock)(id target, id sender);
    
    @interface UIControl (JHBlock)
    
    - (void)jh_handleEvent:(UIControlEvents)events inTarget:(id)target block:(JHUIControlBlock)block;
    
    @end
    

    示例:

    在一个控制器 ( DemoViewController ) 内添加了一个按钮
    添加点击事件

    [button jh_handleEvent:1<<6 inTarget:self block:^(id  _Nonnull target, id  _Nonnull sender) {
            
    }];
    

    把 block 内的参数 id _Nonnull target 修改为 DemoViewController *vc

    [button jh_handleEvent:1<<6 inTarget:self block:^(DemoViewController *vc, id  _Nonnull sender) {
        
            // 这里就可以直接 使用控制器 vc 了
            vc.navigationItem.title = @"修改了标题";
            
            // 调用其他方法
            [vc goNextVC];
            
            // 不再需要使用 Weak-Strong Dance 了
            // 内部对 target ( 这里是指 self ) 是使用的 weak 引用
            // 所以不用担心
    }];
    

    仓库

    地址 : https://github.com/xjh093/JHUIControlBlock


    参考

    相关文章

      网友评论

        本文标题:iOS 不使用 Weak-Strong Dance,怎么避免循环

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