在块中使用弱obj时崩溃

时间:2018-05-14 06:13:28

标签: objective-c automatic-ref-counting block

我的代码是这样的:

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

它很少会崩溃,而这次崩溃的最高筹码就是这样:

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)

执行块时发生崩溃 有谁知道发生了什么事?

1 个答案:

答案 0 :(得分:0)

不需要再次强化自我,删除此行__strong __typeof(weakSelf) self = weakSelf然后应该正常工作

使用此

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

检查执行时失去所有权部分中的https://sectionfive.net/blog/2014/11/24/arc-exploration-and-pitfalls/以获取更多信息