Do I need to check if weak self is nil in blocks?
I create weakSelf pointer like:
__weak typeof(self) weakSelf = self;
and in the beginning of the blocks I do
if(!weakSelf){return;}
is this unnecessary? or does it depend on whether I coded the rest correctly so that when the self dies, others die too?
That check is unnecessary, and is giving you a false sense of security.
Here's the problem:
At
THE LINE OF INTEREST, some other thread might clear the last strong reference toself, at which pointweakSelfis set to nil. So thedoSomethingmessage gets sent to nil, which is “safe” (it does nothing), but might not be what you expected!It's worse if you want to take a different action when
weakSelfis nil, e.g.In this case, between the time the block verifies that
weakSelfis not nil and the time it sends thedoSomethingmessage,weakSelfmight become nil, and neitherdoSomethingnordoSomethingElsewill actually run.The correct solution is this:
In this case, copying
weakSelftostrongSelf(which is strong by default) is atomic. IfweakSelfwas nil,strongSelfwill be nil. IfweakSelfwas not nil,strongSelfwill not be nil, and will be a strong reference to the object, preventing it from being deallocated before thedoSomethingmessage.