Search code examples
objective-cautomatic-ref-countingblock

Crash when use weak obj in block


My code is like this:

Member *member = [Member new];
__weak __typeof(self) weakSelf = self
member.gotoPageBlock = ^(NSString *url) {
    __strong __typeof(weakSelf) self = weakSelf
    [self goToPageWithURL:[NSURL URLWithString:url]];
};

It would crash rarely and the top stack of this crash is like this:

Exception Type:  SIGSEGV
Exception Codes: SEGV_ACCERR at 0x365722298
Triggered by Thread:  0
Thread 0 Crashed:
0   libobjc.A.dylib                 0x0000000182794bb4 _objc_loadWeakRetained :156 (in libobjc.A.dylib)

The crash occurs when executing the block.
Is there anyone know what happened?


Solution

  • Making strong self again is not needed so, remove this line __strong __typeof(weakSelf) self = weakSelf and then should work properly

    Use this

    Member *member = [Member new];
    __weak __typeof(self) weakSelf = self
    member.gotoPageBlock = ^(NSString *url) {
        //the difference is here
        [weakSelf goToPageWithURL:[NSURL URLWithString:url]];
    };
    

    check this https://sectionfive.net/blog/2014/11/24/arc-exploration-and-pitfalls/ in the Losing ownership while executing section for further information