Search code examples
objective-ciosmemory-managementios5automatic-ref-counting

Manual retain with ARC


Before ARC I had the following code that retains the delegate while an async operation is in progress:

- (void)startAsyncWork
{
    [_delegate retain];
    // calls executeAsyncWork asynchronously
}

- (void)executeAsyncWork
{
    // when finished, calls stopAsyncWork
}

- (void)stopAsyncWork
{
    [_delegate release];
}

What is the equivalent to this pattern with ARC?


Solution

  • Why not just assign your delegate object to a strong ivar for the duration of the asynchronous task?

    Or have a local variable in executeAsyncWork

    - (void)executeAsyncWork
    {
        id localCopy = _delegate;
    
        if (localCopy != nil) // since this method is async, the delegate might have gone
        {
            // do work on local copy
        }
    }