Using weak self in dispatch_async function

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.

==========以上是问题========================

==========以下是答案========================

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.(无论是同步还是异步,队列里面的block都将执行)

  • 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 implicitlyretained, 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 yoursecond 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. 
}
});

http://stackoverflow.com/questions/21987067/using-weak-self-in-dispatch-async-function

你可能感兴趣的:(Using weak self in dispatch_async function)