ARC捕获self ...阻塞块内部并在执行之前释放引用 [英] ARC capturing self... block inside a block and reference being released before execution
问题描述
我有这个问题:一个块里面的一个块。
I have this problem: a block inside a block.
self.createStuff = ^ (NSString *text) {
self.post.onCompletion = ^(NSURLResponse *response, NSData *data, NSError *error){
[self doStuff]; // error here
};
[self doMoreStuff]; // error here
};
我将在[self doStuff]和[self doMoreStuff]中出错。错误在此区块中强烈捕获自我可能会导致保留周期
I will have errors in [self doStuff] and on [self doMoreStuff]. The error is capturing 'self' strongly in this block is likely to lead to a retain cycle
很容易说,只需添加
id mySelf = self;
在第一个块之前并改为使用mySelf。
before the first block and use mySelf instead.
不。这不会保存我的问题,只是因为我自己是一个善意的id不会给我一个post属性,第二行需要。所以我需要声明它像
Nope. This will not save my problem, simply because mySelf being of kind id will not give me a post property, needed by the second line. So I need to declare it like
MyClass *mySelf = self;
如下所示:
MyClass *mySelf = self;
self.createStuff = ^ (NSString *text) {
mySelf.post.onCompletion = ^(NSURLResponse *response, NSData *data, NSError *error){
[self doStuff]; // error here
};
[mySelf doMoreStuff];
};
好吧,你说,现在self.post.onCompletion行和doMoreStuff不再抱怨了,但是我们在onCompletion中有另一个self ...因为这是一个块内的块。我可以重复创建另一个弱引用的过程,这将是弱引用的弱引用
OK, you say, now the self.post.onCompletion line and doMoreStuff are not complaining anymore, but we have another self inside onCompletion... because this is a block inside a block. I can repeat the process creating another weak reference like and this will have to be a weak reference to a weak reference
MyClass *internalMyself = mySelf;
并使用
[internalMyself doStuff];
在我看来这是一个非常可怜的方式来做这个以及更多,应用程序挂起时,这个方法运行。在方法执行之前,类似于引用的东西被释放...
this seems to me to be a pretty pathetic way to do this and more, the app hangs when this method runs. Something like the reference is being deallocated before the method executes...
如何解决这个问题?
谢谢。
注意:这是编译到iOS 6 +
note: this is being compiled to iOS 6+
推荐答案
你非常接近。只需更换您的解决方案
You're pretty close. Just replace your solution
MyClass *mySelf = self;
self.createStuff = ^ (NSString *text) {
mySelf.post.onCompletion = ^(NSURLResponse *response, NSData *data, NSError *error) {
[self doStuff]; // error here
};
[mySelf doMoreStuff];
};
with
__weak MyClass *mySelf = self;
self.createStuff = ^ (NSString *text) {
mySelf.post.onCompletion = ^(NSURLResponse *response, NSData *data, NSError *error) {
[self doStuff]; // error here
};
[mySelf doMoreStuff];
};
第一个解决方案的问题是 mySelf
未指定弱
,因此所有权限定符隐式 __ strong
(请参阅LLVM的文档)。我不确定为什么这会在第一个块中消除警告,但是指定引用 __ weak
将完全删除保留周期。
The problem with the first solution is that mySelf
isn't designated weak
, so it's ownership qualifier is implicitly __strong
(see LLVM's documentation). I'm not sure why this quiets the warning in the first block, but designating the reference __weak
will fully remove the retain cycle.
这篇关于ARC捕获self ...阻塞块内部并在执行之前释放引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!