Why not always use weakSelf in a block?

I understand WHY we will use weakSelf in a block, just not so much.

I am converting a codebase to ARC, which gives a lot of warnings to the save cycle with blocks. From the documentation I compiled, I need to change this:

[self.selectedAsset addToFavoritesWithCompletion:^(NSError *error) { self.selectedAsset.isFavorite = YES; [self updateIsFavoriteButton]; }]; 

:

 __weak MyViewController* weakSelf = self; [self.selectedAsset addToFavoritesWithCompletion:^(NSError *error) { self.selectedAsset.isFavorite = YES; [weakSelf updateIsFavoriteButton]; }]; 

To make the compiler happy and avoid holding loops. My question is: why is there no need to change the line:

 self.selectedAsset.isFavorite = YES; 

use weakSelf? Does this evaluate the method invocation method? Why does the compiler not warn about strings in this format?

 [[self selectedAsset]setIsFavorite:YES]; 

EDIT: I am just upgrading to Xcode 4.6, and now it only generates compiler warnings for this situation. Funny time :)

+7
source share
2 answers

My question is: why don't you need to change the line:

self.selectedAsset.isFavorite = YES; use weakSelf ? Isn't it to evaluate the calling method? Why does the compiler not warn about strings in this format?

[[self selectedAsset]setIsFavorite:YES];

Yes, this is a method call. And it really gives a strong reference to self . And you need to change it to weakSelf if you want it to not save self .

Compiler warnings will not catch everything.

+8
source
 __weak MyViewController* weakSelf = self; [self.selectedAsset addToFavoritesWithCompletion:^(NSError *error) { self.selectedAsset.isFavorite = YES; [weakSelf updateIsFavoriteButton]; }]; 

really stupid. The completion block referred to self twice, which would create a strong link. It still refers to the self once, which still creates a strong link. And weak links are pointless if you also use strong links. It should be

 __weak MyViewController* weakSelf = self; [self.selectedAsset addToFavoritesWithCompletion:^(NSError *error) { weakSelf.selectedAsset.isFavorite = YES; [weakSelf updateIsFavoriteButton]; }]; 

or better (because it's safer)

 __weak typeof (self) weakSelf = self; [self.selectedAsset addToFavoritesWithCompletion:^(NSError *error) { typeof (self) strongSelf = weakSelf; strongSelf.selectedAsset.isFavorite = YES; [strongSelf updateIsFavoriteButton]; }]; 
+1
source

All Articles