【问题标题】:Crash when use weak obj in block在块中使用弱 obj 时崩溃
【发布时间】:2018-10-23 17:47:39
【问题描述】:

我的代码是这样的:

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)

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

【问题讨论】:

  • 代码没有问题。问题一定出在其他地方。

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


【解决方案1】:

不需要再次制作强大的自我,所以删除这行__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/ 以获取更多信息

【讨论】:

  • 也许这是一个解决方案,但我想知道为什么会发生这种崩溃。
  • @user3016644 在执行时失去所有权部分查看sectionfive.net/blog/2014/11/24/arc-exploration-and-pitfalls以获取更多信息
  • 如果块内有两个weakSelf 调用会发生什么?
  • 这和OP的代码没有语义上的区别
  • @newacct 你确定吗?再读一遍,OP 使 self 在块内变得强大
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-12-11
  • 1970-01-01
  • 1970-01-01
  • 2015-07-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多