Using weak self in dispatch_async function

Marko Zadravec picture Marko Zadravec · Feb 24, 2014 · Viewed 36.6k times · Source

I read a lot of posts about using __weak self inside dispatch_async, and now I am a litle bit confused.

if I have :

self.myQueue = dispatch_queue_create("com.biview.core_data", NULL);

dispatch_async(self.myQueue, ^(void){
    if (!self.var1) {
        self.var1 = ...;
    }
    dispatch_async(dispatch_get_main_queue(), ^(void) {
        if ([self.var2 superview]) {
            [self.var2 removeFromSuperview];
        }

        [self.Label setText:text];
    });
});

do I need to use __weak self. Because I read that in some cases dispatch_async not need a __weak self.

See last comment here

Answer

CouchDeveloper picture CouchDeveloper · Feb 24, 2014

Assuming, self is an object pointer to a UIViewController.

Things to consider:

  • A UIViewController is a "UIKit" object. UIKit objects shall not be sent methods on non-main threads, that is - those methods must execute on the main thread only!

  • A block that has been enqueued in a queue - whether this was synchronously or asynchronously - will eventually be executed -- no matter what! Well, unless the program terminates before this can happen.

  • Captured retainable strong pointers will be retained when the block will be copied (for example, when dispatched asynchronously), and again released when the block will be destroyed (after it finished).

  • Captured retainable weak pointers will NOT be retained and not released.

In your scenario, where you capture self in the block which is dispatched on the main queue, you don't need to worry that bad things happen.

So, why? And what happens actually?

Since self will be captured in the block which is dispatched asynchronously, self will be implicitly retained, and released again when the block has been finished.

That means, the life-time of self will be extended up until after the block finishes. Notice that your second block is dispatched on the main thread, and it's guaranteed that self is still alive when that block gets executed.

This "extended life" above, might be a desired feature of your program.

If you explicitly don't want to extend the life-time of the UIViewController object, and instead want the block - when it finally executes - check whether this UIViewController object does still exist at all, you can use a __weak pointer of self. Note that the block gets eventually executed, no matter whether the UIViewController is still alive or has been deallocated in the mean time.

You might want the block doing "nothing" if the UIViewController has been deallocated before the block will get executed:

MyController* __weak weakSelf = self;
dispatch_async(queue, ^{
    MyController* strongSelf = weakSelf;
    if (strongSelf) {
        ...
    }
    else {
       // self has been deallocated in the meantime.
    }
});

See also: Transitioning to ARC Release Notes

Remember: UIKit objects shall not be sent methods on non-main threads!

One other subtle error may occur due to the fact that UIKit objects shall execute methods only on the main thread.

This can be violated, if a block captures a UIKit object which is dispatched asynchronously, and executes on a non-main thread. It then may happen that the block holds the last strong reference to that UIKit object. Now, when the block gets eventually executed, the block will be destroyed and the UIKit object will be released. Since this is the last strong reference to the UIKit object, it will be deallocated. However, this happens on the thread where the block has been executed - and this is not the main thread! Now, bad things can (and will usually) happen, since the dealloc method is still a method sent to a UIKit object.

You can avoid this error, by dispatching a block capturing a strong pointer to that UIKit object, and send it a dummy method:

UIViewController* strongUIKitPointer = ... 
dispatch_async(non_main_queue, ^{
    ... // do something 
    dispatch(dispatch_get_main_queue(), ^{
        [strongUIKitPointer self];  // note: self is a method, too - doing nothing
    });
});

In your scenario though, the last strong reference could be only in the block which executes on the main thread. So, you are safe from this subtle error. ;)

Edit:

In your setup, you never have a retain cycle. A retain cycle occurs if a retainable object A strongly references another retainable object B, and object B strongly references A. Note that a "Block" is also a retainable object.

A contrived example with a cyclic reference:

typedef void(^my_completion_block_t)(NSArray* result);

@interface UsersViewController : UIViewController
@property (nonatomic, copy) my_completion_block_t completion;
@property (nonatomic) NSArray* users;
@end

Here, we have a property completion whose value type is a Block. That is, we get an ivar with name _completion whose type is a Block.

A client may set a completion handler which should be called when a certain operation has finished. Suppose, the operation fetches a list of Users from a remote server. The plan is to set the property users once the operation finished:

The careless approach would accidentally introduce a cyclic reference:

Somewhere in "UsersViewController.m"

self.completion = ^(NSArray* users){
    self.users = users;
}

[self fetchUsers];  // start asynchronous task

Here, self holds a strong reference to the ivar _completion, which is a block. And the block itself captures self, which causes to retain self when the block gets copied when it is dispatched. This is a classic reference cycle.

In order to avoid that cyclic reference, we have a few alternatives:

  1. Using a __weak qualified pointer of self

    UsersViewController* __weak weakSelf = self;
    self.completion = ^(NSArray* users) {
        UsersViewController* strongSelf = weakSelf;
        if (strongSelf) {
            strongSelf.users = users;
        }
        else {
            // the view controller does not exist anymore
        }
    }   
    [usersViewController fetchUsers];
    
  2. Using a __block qualified pointer of self and eventually setting it nil in the block when it finishes:

    UsersViewController* __block blockSelf = self;
    self.completion = ^(NSArray* users) {
        blockSelf.users = users;
        blockSelf = nil;
    }   
    [usersViewController fetchUsers];
    

See also: Transitioning to ARC Release Notes