Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 964
griotspeak Avatar asked Aug 10 '12 09:08

griotspeak


1 Answers

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.

like image 161
griotspeak Avatar answered Nov 16 '22 01:11

griotspeak