objective c - EXC_BAD_ACCESS when using weakSelf in block / blocks -
i have been struggeling issue while since don't think understand retain cycles. totally new , i'm trying learn more it.
i getting exc_bad_access message following code.
i started using weakself because 2 warnings retain cycle if use self.successblock();. exact warning is:
capturing 'self' in block lead retain cycle
maybe shouldn't bother using weak no sure this.
this part use weakself in 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 how assign 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;
a __weak
reference set nil
if object points deallocated. if request
object has been deallocated when completion block called, weakself
nil
. in case weakself.successblock
evaluates null pointer, , causing crash.
the following pattern avoids problem:
[_operation setcompletionblockwithsuccess:^(afhttprequestoperation *operation, id responseobject) { request *strongself = weakself; if (strongself) { strongself.successblock(operation.response, responseobject); } } ...
strongself
nil
if request
object has been deallocated. otherwise strong reference ensures object not deallocated while block executing.
on other hand, if want request
object exist until completion block called, should not use weak reference.
Comments
Post a Comment