在一个或多个块中使用weakSelf时使用EXC_BAD_ACCESS [英] EXC_BAD_ACCESS when using weakSelf in block / blocks
问题描述
我一直在努力解决这个问题,因为我认为我不完全了解保留周期.我对此是完全陌生的,我正在尝试了解有关它的更多信息.
I have been struggeling with this issue for a while since i don't think i fully understand the retain cycles. I am totally new to this and i'm trying to learn more about it.
我收到带有以下代码的EXC_BAD_ACCESS消息.
I am getting the EXC_BAD_ACCESS message with the following code.
我开始使用weakSelf,因为如果我仅使用self.successBLock();会收到2条有关保留周期的警告.确切的警告是:
I started using the weakSelf because i get 2 warnings about the retain cycle if i just use self.successBLock();. The exact warning is:
Capturing 'self' strongly in this block is likely to lead to a retain cycle
也许我什至不应该使用弱者,但我对此不太确定.
Maybe i shouldn't even bother using the weak but i am no so sure about this.
这是我在一个块中使用weakSelf的部分:
This is the part where i use the weakSelf in a block:
__weak Request *weakSelf = self;
[_operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
weakSelf.successBlock(operation.response, responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
weakSelf.failureBlock(operation.response, error);
}];
这是我分配块属性的方式:
This is how i assign the block properties:
typedef void (^successBlock)(NSHTTPURLResponse *response, id responseObject);
typedef void (^failureBlock)(NSHTTPURLResponse *response, NSError *error);
@property (nonatomic, copy) successBlock successBlock;
@property (nonatomic, copy) failureBlock failureBlock;
推荐答案
如果__weak
引用所指向的对象被释放,则将其设置为nil
.
因此,当完成块为时,如果您的Request
对象已经被释放,
称为weakSelf
是nil
.在这种情况下,weakSelf.successBlock
的计算结果为NULL指针,这将导致崩溃.
A __weak
reference is set to nil
if the object it points to is deallocated.
So if your Request
object has already been deallocated when the completion block is
called, weakSelf
is nil
. In that case weakSelf.successBlock
evaluates to a NULL pointer, and that is causing the crash.
以下模式可以避免此问题:
The following pattern avoids this problem:
[_operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
Request *strongSelf = weakSelf;
if (strongSelf) {
strongSelf.successBlock(operation.response, responseObject);
}
} ...
如果Request
对象已经被释放,则
strongSelf
将为nil
.
否则,强引用将确保不释放对象
在执行块时.
strongSelf
will be nil
if the Request
object has already been deallocated.
Otherwise the strong reference ensures that the object is not deallocated
while the block is executing.
另一方面,如果您希望Request
对象存在直到完成块
被调用,那么您不应使用弱引用.
On the other hand, if you want the Request
object to exist until the completion block
is called, then you should not use a weak reference.
这篇关于在一个或多个块中使用weakSelf时使用EXC_BAD_ACCESS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!