Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objective-C ARC - does a method retain 'self'? [duplicate]

Is this a safe thing to do?

__weak typeof (self) welf = self;
dispatch_async(dispatch_get_main_queue(), ^{
    [welf doStuff];
})

....

-(void)doStuff {
    [_member1 someMethod];
    ....
    [_member2 someMethodWithParam:_someCArray[1];];
}

As far as I understand ARC, the actual call to [welf doStuff] should be fine, as welf will either be valid (and the method call will proceed), or it will be nil - calling any method on nil is defined safe behaviour in Objective-C so that seems ok.

Once we get into doStuff however, does ARC cause self to be retained for the duration of the method call? If it does, I think we should be ok... If not, then self could get dealloc'ed halfway through the method call and then we'd be in a bad spot.

Note: I googled for this but couldn't find anything obvious. Perhaps it's just hard to search for?

Thanks!

like image 672
Orion Edwards Avatar asked Oct 17 '25 02:10

Orion Edwards


1 Answers

As it turns out I found the answer eventually, both here: https://stackoverflow.com/a/18011581/234 and here: http://clang.llvm.org/docs/AutomaticReferenceCounting.html#self

self is always unsafe unretained under ARC, so in my example, it would NOT be safe, and there would be nothing to stop it getting deallocated partway through my doStuff method. Ouch

like image 153
Orion Edwards Avatar answered Oct 18 '25 17:10

Orion Edwards