Reputation: 157
I have this code:
@implementation example
{
NSString *myObject;
}
- (void)viewDidLoad
{
[super viewDidLoad];
__block NSString* blockObject = myObject;
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0),^(void){
blockObject = @"Hello world";
});
}
Now because I am using __block, a strong reference is made to self, because I am accessing an instance variable by reference and not by value.
So the above code is the same as:
@implementation example
{
NSString *myObject;
}
- (void)viewDidLoad
{
[super viewDidLoad];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH,0),^(void) {
myObject = @"Hello world";
});
}
So dealloc method will not called until the block exit. My compiler use arc!
Upvotes: 1
Views: 138
Reputation: 39978
__block NSString* blockObject = myObject;
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0),^(void){
blockObject = @"Hello world";
});
The above code will not strongly hold the self
and thus your dealloc
will be called before the block
exits. Why it will not strongly hold the self
is because you are creating a new variable blockObject
and block will strongly hold this variable not the ivar thus not retaining the self
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH,0),^(void) {
myObject = @"Hello world";
});
The above code will strongly hold the self
and dealloc
will not be called until block
exits.
Upvotes: 1
Reputation: 10195
The two example in your question are in fact very different.
The first results in NO CHANGE to your instance variable myObject
whereas the second changes it to "Hello world".
Upvotes: 1
Reputation: 4654
Usually if I have to access instance variables, I write something like this... fyi. pseudocode
__weak typeof(self)weakSelf = self;
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH,0),^(void) {
__strong typeof(weakSelf)strongSelf = weakSelf;
strongSelf->myObject = @"Hello world";
});
Upvotes: 0