How to properly address “Weak receiver may be unpr

2019-03-09 03:11发布

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条回答
时光不老,我们不散
2楼-- · 2019-03-09 03:51

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.

查看更多
登录 后发表回答