疑惑
以下是引用:
這是來自 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
參考
1.使用 Heap-Stack Dance 替代 Weak-Strong Dance,優(yōu)雅避開循環(huán)引用
http://www.itdecent.cn/p/60a495270f4b2.不做從strong 到weak 的轉(zhuǎn)換,如何避免循環(huán)引用
https://blog.csdn.net/tangaowen/article/details/468228833.iOS Development Tips
Tip: Avoid retain cycles without doing the strong to weak dance
http://iosdevtips.co/post/118711491198/avoid-retain-cycles-weak-strong4.iOS 之 UIControl 的 Block 響應(yīng)方式
https://blog.csdn.net/three_zhang/article/details/72964329