Should I use "weakSelf" in the control unit?

I heard that I should always use weakSelf in blocks to avoid save loops, but what about send blocks? In this case, my method processes the error response from my server in the following code:

 //handling server errors (particularly "Token Refresh Failed" ones) -(void)handleServerErrorResponse:(NSString *)error { dispatch_async(dispatch_get_main_queue(), ^{ UIAlertController *alertController = [DialogHelper getAlertForSimpleAuthError:error]; if ([error isEqualToString:@"Your login session has expired"]) { [alertController addAction:[UIAlertAction actionWithTitle:@"Ok" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) { [MyModelDataCenter emptyDataCenter]; [MyAPIInterface sharedInstance].authToken = nil; NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults]; [defaults removeObjectForKey:@"authToken"]; [defaults removeObjectForKey:@"defaultUserObjectDictionary"]; [defaults synchronize]; [AuthenticationHelper sharedInstance].loggedInUser = nil; [self.navigationController popToRootViewControllerAnimated:YES]; }]]; } else { [alertController addAction:[UIAlertAction actionWithTitle:@"Ok" style:UIAlertActionStyleDefault handler:nil]]; } [self presentViewController:alertController animated:YES completion:nil]; }); } 

Should I use weakSelf in this block in the same way as in other blocks?

+5
source share
2 answers

You need to use a weak strong “dance” to avoid a hold cycle only with a constant save cycle. To do this, two conditions must be met:

  • The block belongs to the object referenced inside the block.
  • the owner does not release the block until his own release

If one of these things is wrong, there is no permanent save cycle and no problems.

In this case, none is true. In general, Blocks placed in the dispatch queue will not be stored in cycles unless you use the block in Ivar for reuse.

+8
source

Even I agree with Josh and agree from the very beginning that there is no reason to weaken self , if it is not necessary (the block is not held by the reference object), in the past most weak self by default. (I think most are changing.)

However, there may be a reason for loosening self , even if there is no save loop:

An image in which you have an instance object filled with a long block. Perhaps the instance object will die while the block is running, i.e. e. because the user deleted it. In this case, the block will populate the instance object, which is no longer used, and left your model, but is still alive, because the block holds it. By loosening it, it will free it and set the captured self to nil , which is easy to verify and usually just does nothing.

But I really don’t think and never thought that this scenario justifies the rule of thumb “Weakify by default”.

+5
source

Source: https://habr.com/ru/post/1241682/


All Articles