iOS 不使用 Weak-Strong Dance,怎么避免循環(huán)引用?

疑惑

以下是引用:

這是來自 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);

這個(gè)block里面的參數(shù),從某種意義上來說,是冗余的。因?yàn)槟銖腷lock中總是能夠 顯式的引用到任何的外部對象。
但是它是非常有用的,因?yàn)楝F(xiàn)在你能夠使用參數(shù),而不是做一個(gè) weak 的引用。

之前看到這個(gè)的時(shí)候,一直沒想明白
直到后來看了這篇文章
使用 Heap-Stack Dance 替代 Weak-Strong Dance,優(yōu)雅避開循環(huán)引用
的詳細(xì)介紹后
才明白


正題

之前有看到過
iOS 之 UIControl 的 Block 響應(yīng)方式
這種使用方式
缺點(diǎn)是需要使用 Weak-Strong Dance
來避免循環(huán)引用

于是
我就想著
既然明白了不使用 Weak-Strong Dance 就能避免循環(huán)引用的道理
為何不改進(jìn)一下 UIControl 的 Block 響應(yīng)方式 呢?


實(shí)現(xiàn)

參考 BlocksKit 中 UIControl+BlocksKit.m的實(shí)現(xiàn)方式

實(shí)現(xiàn)如下:

.h

typedef void(^JHUIControlBlock)(id target, id sender);

@interface UIControl (JHBlock)

- (void)jh_handleEvent:(UIControlEvents)events inTarget:(id)target block:(JHUIControlBlock)block;

@end

示例:

在一個(gè)控制器 ( DemoViewController ) 內(nèi)添加了一個(gè)按鈕
添加點(diǎn)擊事件

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

把 block 內(nèi)的參數(shù) id _Nonnull target 修改為 DemoViewController *vc

[button jh_handleEvent:1<<6 inTarget:self block:^(DemoViewController *vc, id  _Nonnull sender) {
    
        // 這里就可以直接 使用控制器 vc 了
        vc.navigationItem.title = @"修改了標(biāo)題";
        
        // 調(diào)用其他方法
        [vc goNextVC];
        
        // 不再需要使用 Weak-Strong Dance 了
        // 內(nèi)部對 target ( 這里是指 self ) 是使用的 weak 引用
        // 所以不用擔(dān)心
}];

倉庫

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


參考

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容