带有块和保留周期的ARC [英] ARC with blocks and retain cycles
问题描述
我有一个将块作为对象属性的类:
I have a class which holds a block as an object property:
@property (nonatomic, readwrite, copy) SFFailureBlock failureBlock;
其中SFFailureBlock:
where SFFailureBlock:
typedef void (^SFFailureBlock)(NSError *error);
我还有一个也声明为对象属性(AFHTTPRequestOperation)的操作,我希望它在完成后调用故障块.
I have an operation also declared as an object property (AFHTTPRequestOperation) and I want it to call the failure block once it is completed.
[self.operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
__weak NSError *error = [NSError errorWithDomain:@"com.test" code:100 userInfo:@{@"description": @"zero results"}];
failureBlock(error);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"nothing");
}];
我得到一个编译器警告在此块中强烈捕获'self'可能会导致保留周期".我已经在互联网上进行搜索,但是找不到为什么会导致保留周期的体面解决方案.我不在任何地方都称呼自己为自我".
I get a compiler warning "Capturing 'self' strongly in this block is likely to lead to a retain cycle". I have searched the internet but I couldn't find a decent solution as to why this leads to a retain cycle. I am not calling 'self' inside the block anywhere.
另一个奇怪的事情是,如果我写了'self.failureBlock(error)',编译器不会给我任何警告!
Another strange thing is that if I write 'self.failureBlock(error)' the compiler does not give me any warning!
有人可以向我解释发生了什么吗?我必须严重丢失ARC内存管理规则中的某些内容,但我无法弄清楚.
Can anyone explain to me what is going on? I must be seriously missing something in ARC memory management rules, but I can't figure it out.
推荐答案
在操作块中引用"failureBlock"时,实际上是在做"self-> failureBlock",因此它隐式保留了self.您可以做的是创建一个自动变量SFFailureBlock xFailureBlock = failureBlock;.上面的自我操作,然后在块中使用它. [同样,您也要避免在它们内部阻止任何self->引用.]
When you refer to "failureBlock" in the operation's block, you are really doing "self-> failureBlock" - so it implicitly retains self. What you can do is create an automatic variable SFFailureBlock xFailureBlock = failureBlock; above the selfoperation, then use it in the block. [Again, you want to avoid any self-> references INSIDE that block either.]
这篇关于带有块和保留周期的ARC的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!