VaporwareWolf VaporwareWolf - 1 year ago 70
Objective-C Question

Why not always use weakSelf in a block?

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 :)

Answer Source

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];

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download