You are here

Self in blocks

This topic shows best practice for using references to self from within completion blocks.

To avoid retain cycles, the reference to the object being used inside a completion block must be weak. Therefore, outside of the block do the following:

          
          __weak <YourClassName> *weakSelf = self;        
          
        

Inside the block use the reference to the object as follows:

          
          [weakself doSomething];
          
        

The following example illustrates this technique:


__weak DocumentViewController *weakSelf = self;
[self.documentService retrieveRenditionOfNode:self.document renditionName:kAlfrescoThumbnailRendition 
    completionBlock:^(AlfrescoContentFile *contentFile, NSError *error)
{
  if (nil != contentFile)
  {
    NSData *data = [[NSFileManager defaultManager] contentsAtPath:[contentFile.fileUrl path]];
    weakSelf.thumbnail = [UIImage imageWithData:data];
    [weakSelf.tableView reloadSections:[NSIndexSet indexSetWithIndex:0] withRowAnimation:UITableViewRowAnimationNone];
}}];