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

后端 未结 1 1659
生来不讨喜
生来不讨喜 2021-01-31 19:54

I turned on a new flag in xcode and get the warning \"Weak receiver may be unpredictably null in ARC mode\". This confuses me because OF COURSE it could be nil.

相关标签:
1条回答
  • 2021-01-31 20:31

    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.

    0 讨论(0)
提交回复
热议问题