I understand WHY we would use weakSelf in a block, just not so much when.
I am converting a codebase to ARC which gives a lot of retain cycle warnings with blocks. From the documentation I've gathered that I need to change this:
[self.selectedAsset addToFavoritesWithCompletion:^(NSError *error) {
self.selectedAsset.isFavorite = YES;
[self updateIsFavoriteButton];
}];
to this:
__weak MyViewController* weakSelf = self;
[self.selectedAsset addToFavoritesWithCompletion:^(NSError *error) {
self.selectedAsset.isFavorite = YES;
[weakSelf updateIsFavoriteButton];
}];
To make the compiler happy and avoid retain loops. My question is why isn't it necessary to change the line:
self.selectedAsset.isFavorite = YES;
to use weakSelf? Doesn't it evaluate to a method call as well? Why doesn't the compiler warn about lines in this format?
[[self selectedAsset]setIsFavorite:YES];
EDIT: I just update to XCode 4.6, and it now generates compiler warnings for just this situation. Funny timing :)
My question is why isn't it necessary to change the line:
self.selectedAsset.isFavorite = YES;
to useweakSelf
? Doesn't it evaluate to a method call as well? Why doesn't the compiler warn about lines in this format?
[[self selectedAsset]setIsFavorite:YES];
Yes, it is exactly a method call. And it does cause a strong reference to self
. And it IS necessary to change it to weakSelf
if you want it to not retain self
.
Compiler warnings do not catch everything.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With