Objective-C/块-这不是保留周期吗? [英] Objective-C / Blocks - Isn't this a retain cycle?
本文介绍了Objective-C/块-这不是保留周期吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
@interface ClassA : NSObject
@property (strong, nonatomic) dispatch_queue_t dispatchQ;
@property (strong, nonatomic) NSString *string;
@end
@implementation ClassA
- (id)init
{
self = [super init];
if (self) {
_dispatchQ = dispatch_queue_create("com.classa.q", NULL);
}
return self;
}
- (void)longRunningTaskWithCompletion:(void(^)(void))completion
{
dispatch_async(self.dispatchQ, ^{
for (int i = 0; i < 10000; i++) {
NSLog(@"%i", i);
}
dispatch_sync(dispatch_get_main_queue(), ^{
self.string = @"Class A Rocks!";
if(completion) {
completion();
}
});
});
}
@end
我想这段代码会创建一个保留周期,因为-longRunningTaskWithCompletion:
中的块将自身(设置字符串属性)捕获到一个块中并将该块添加到调度队列属性中.
I'm thinking this code creates a retain cycle because the block in -longRunningTaskWithCompletion:
captures self (to set the string property) in a block and adds the block to the dispatch queue property.
推荐答案
有一个保留周期,但这是临时的.保留周期如下:
There is a retain cycle, but it's temporary. The retain cycle looks like this:
-
self
保留dispatchQ
-
dispatchQ
保留该块 - 该图块保留
self
self
retainsdispatchQ
dispatchQ
retains the block- the block retains
self
当块返回时,dispatchQ
释放它.在这一点上,保留周期被打破了.释放该块并释放self
.
When the block returns, dispatchQ
releases it. At that point, the retain cycle is broken. The block is deallocated and releases self
.
这篇关于Objective-C/块-这不是保留周期吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文