How to properly address “Weak receiver may be unpredictably null in ARC mode”

限于喜欢 提交于 2019-12-02 18:41:24

I asked this question a week ago and received no answer, but Greg Parker answered it on the mailing list. So I am reposting with the answer.

We added this warning because we saw lots of subtle and hard to debug problems in practice.

The recommended practice is to read the weak variable into a strong local variable once, and then use the local variable.

  • Greg Parker

In my first incarnation of this question, I posted something like this, where I thought testing for nil should have been enough

if (self.rootViewController) {
    [self.rootViewController controllerWillChangeContent:controller];
}

The problem is that self.rootViewController could BECOME nill in the space between checking for nil and completing the method called. What we are told to do is to assign to a strong local reference and use that like so

- (void)controllerWillChangeContent:(NSFetchedResultsController *)controller {
    RootViewController *rootVC = self.rootViewController;
    if (rootVC) {
        [rootVC controllerWillChangeContent:controller];
    }
}

Stephen Butler presented succinct restatement of the problem this warning is meant to combat

What we're trying to prevent is the object instance getting dealloced while you're in [someMethod] because you called it off a weak reference and nothing is holding onto the object strongly.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!