I’m using an NSOperationQueue and queuing up NSOperationBlocks. Now, blocks have a strong reference to any instances in the block, and the calling object also has a strong hold on the block, so it has been advised to do something like the following:
__weak Cell *weakSelf = self;
NSBlockOperation *op = [NSBlockOperation blockOperationWithBlock:^{
UIImage *image = /* render some image */
/* what if by the time I get here self no longer exists? */
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
[weakSelf setImageViewImage:image];
}];
}];
[self.renderQueue addOperation:op];
So, my question is, let’s say that by the time the image finishes rendering and that line comes back, the Cell object no longer exists (it has been deallocated, possibly due to cell reuse, which is a bit difficult to formalize). When I go to access [weakSelf setImageViewImage:], will that cause a EXC_BAD_ACCESS error?
Currently I’m trying to trace what the cause of my problem is, and I’m thinking it might have something to do with this.
So,
__weakis a zeroing weak reference. What this means is that during your operation,selfmay indeed be deallocated, but all weak references to it (namelyweakSelf) will be zeroed out. This means that[weakSelf setImageViewImage:image]is just sending a message tonil, which is safe; or, at least, it shouldn’t cause anEXC_BAD_ACCESS. (Incidentally, if you had qualifiedweakSelfas__unsafe_unretained, you might end up sending messages to a freed object.)So, I doubt that sending a message to a
__weakreference is causing a crash. If you want to ensure thatselfsurvives for the length of your operation, you can get a strong reference to the weak one in the block scope: