Retain cycle on `self` with blocks(使用块在“self上保留循环)
问题描述
I'm afraid this question is pretty basic, but I think it's relevant to a lot of Objective-C programmers who are getting into blocks.
What I've heard is that since blocks capture local variables referenced within them as const
copies, using self
within a block can result in a retain cycle, should that block be copied. So, we are supposed to use __block
to force the block to deal directly with self
instead of having it copied.
__block typeof(self) bself = self;
[someObject messageWithBlock:^{ [bself doSomething]; }];
instead of just
[someObject messageWithBlock:^{ [self doSomething]; }];
What I'd like to know is the following: if this is true, is there a way that I can avoid the ugliness (aside from using GC)?
Strictly speaking, the fact that it's a const copy has nothing to do with this problem. Blocks will retain any obj-c values that are captured when they are created. It just so happens that the workaround for the const-copy issue is identical to the workaround for the retain issue; namely, using the __block
storage class for the variable.
In any case, to answer your question, there's no real alternative here. If you're designing your own block-based API, and it makes sense to do so, you could have the block get passed the value of self
in as an argument. Unfortunately, this doesn't make sense for most APIs.
Please note that referencing an ivar has the exact same issue. If you need to reference an ivar in your block, either use a property instead or use bself->ivar
.
Addendum: When compiling as ARC, __block
no longer breaks retain cycles. If you're compiling for ARC, you need to use __weak
or __unsafe_unretained
instead.
这篇关于使用块在“self"上保留循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用块在“self"上保留循环


基础教程推荐
- AdMob 广告未在模拟器中显示 2022-01-01
- iPhone - 获取给定地点/时区的当前日期和时间并将其与同一地点的另一个日期/时间进行比较的正确方法 2022-01-01
- Cocos2d iPhone 非矩形精灵触摸检测 2022-01-01
- NSString intValue 不能用于检索电话号码 2022-01-01
- iOS4 创建后台定时器 2022-01-01
- navigator.geolocation.getCurrentPosition 在 Android 浏览器上 2022-01-01
- 通过重定向链接在 Google Play 中打开应用 2022-01-01
- libGDX 从精灵或纹理中获取像素颜色 2022-01-01
- Android:getLastKnownLocation(LocationManager.NETWORK_PROVIDER 2022-01-01
- 如何从 logcat 中删除旧数据? 2022-01-01