more info ⬇

@amattn

subscribe for the best
iOS code & business tips:

iOS, server tech, and the business of software



2011 12 07

ARC Best Practices

Some optional backstory:

The advice here assumes you are using iOS 5 or greater, not 4. In practice, weak pointers are such an important tool in ARC, that I don’t recommend using ARC in iOS 4.

Note on updates

This document has been continuously updated to the very best of my ability since it was originally published back in 2011. The last minor revisions are from 2013 bringing the document current with iOS 7.

General

Bridging

From the documentation:

id my_id;
CFStringRef my_cfref;
NSString   *a = (__bridge NSString*)my_cfref;     // Noop cast.
CFStringRef b = (__bridge CFStringRef)my_id;      // Noop cast.
NSString   *c = (__bridge_transfer NSString*)my_cfref; // -1 on the CFRef
CFStringRef d = (__bridge_retained CFStringRef)my_id;  // returned CFRef +1

Translated from nerd-speak into slightly-less-nerd-speakish:

NSError

The ubiquitous NSError is a little bit tricky. Typical Cocoa convention is that they are implemented via out-parameters (aka indirect pointers).

In ARC, out-parameters are by default __autoreleasing and should be implemented like this:

- (BOOL)performWithError:(__autoreleasing NSError **)error
{
    // ... some error occurs ...
    if (error)
    {
        // write to the out-parameter, ARC will autorelease it
        *error = [[NSError alloc] initWithDomain:@"" 
                                            code:-1 
                                        userInfo:nil];
        return NO;
    }
    else
    {
        return YES;
    }
}

When using an out-parameter, you will usually use __autoreleasing on your *error object like so:

NSError __autoreleasing *error = error;
BOOL OK = [myObject performOperationWithError:&error];
if (!OK)
{
    // handle the error.
}

If you forget the __autoreleasing, the compiler will simply insert a temporary, intermediate autoreleasing object for you. This was a compromise made under the oppressive regime of backwards compatibility. I have seen some compiler configurations which do not automatically make them __autoreleasing. It is safer to include the __autoreleasing for all new code.

@autoreleasepool

Use @autoreleasepool inside loops that:

Creating and destroying autorelease pools using the @autoreleasepool directive is cheaper than a blue light special. Don’t worry about doing it inside the loop. If you are super-paranoid, at least check the profiler first.

Blocks

In general, blocks just work. There are a few exceptions however.

When adding block pointers to a collection, you need to copy them first.

someBlockType someBlock = ^{NSLog(@"hi");};
[someArray addObject:[someBlock copy]];

Retain cycles are somewhat dangerous with blocks. You may have seen this warning:

warning: capturing 'self' strongly in this 
block is likely to lead to a retain cycle 
[-Warc-retain-cycles,4]

SomeBlockType someBlock = ^{
    [self someMethod];
};

The reason is that someBlock is strongly held by self and the block will “capture” and retain self when/if the block is copied to the heap.

In a less obvious manifestation of the same potential retain cycle, any ivar you use will also capture the parent object:

// The following block will retain "self"
SomeBlockType someBlock = ^{
    BOOL isDone = _isDone;  // _isDone is an ivar of self
};

The safer, but loquacious workaround is to use a weakSelf:

__weak SomeObjectClass *weakSelf = self;

SomeBlockType someBlock = ^{
    SomeObjectClass *strongSelf = weakSelf;
    if (strongSelf == nil)
    {
        // The original self doesn't exist anymore.
        // Ignore, notify or otherwise handle this case.
    }
    else
    {
        [strongSelf someMethod];
    }
};

Sometimes, you need to take care to avoid retain cycles with arbitrary objects: If someObject will ever strongly hold onto the block that uses someObject, you need weakSomeObject to break the cycle.

SomeObjectClass *someObject = ...
__weak SomeObjectClass *weakSomeObject = someObject;

someObject.completionHandler = ^{
    SomeObjectClass *strongSomeObject = weakSomeObject;
    if (strongSomeObject == nil)
    {
        // The original someObject doesn't exist anymore.
        // Ignore, notify or otherwise handle this case.
    }
    else
    {
        // okay, NOW we can do something with someObject
        [strongSomeObject someMethod];
    }
};

Accessing CGThings from NSThings or UIThings

UIColor *redColor = [UIColor redColor]; 
CGColorRef redRef = redColor.CGColor;
// do some stuff with redRef.

The above example has some very subtle problems. When you create redRef, if redColor is never used again, then redColor is destroyed right after the comment.

The problem is that redColor “owns” redRef, and when redRef is accessed, it may or may not be a colorRef anymore. Even worse, is that this type of error rarely shows up on the simulator. It’s more likely to occur when used on a device with lower working memory, like the original iPad.

There are a couple of workarounds. Essentially, you just want to keep redColor alive while you use redRef.

One very easy way to accomplish this is to use __autoreleasing.

UIColor * __autoreleasing redColor = [UIColor redColor];
CGColorRef redRef = redColor.CGColor;

Now, redColor isn’t destroyed until some indeterminate time later, well after the method returns. We can safely use redRef in the scope of our method.

Another way is to retain the redRef:

UIColor *redColor = [UIColor redColor];
CGColorRef redRef = CFRetain(redColor.CGColor);
// use redRef and when done release it:
CFRelease(redRef)

It’s important to note that you need CFRetain() on the same line where you use redColor.CGColor. redColor is effectively destroyed after the last time you use it. The following will NOT work:

UIColor *redColor = [UIColor redColor];
CGColorRef redRef = redColor.CGColor; // redColor is released right after this...
CFRetain(redRef);  // This may crash...
...

One interesting note on the line marked “This may crash” above. Again, in my experience, it doesn’t crash very often in the simulator, but does crash fairly reliably on actual iOS devices. Caveat Developor.

The Big Nerd Ranch has a very deep dive into this issue: http://weblog.bignerdranch.com/?p=296

Singletons

Only incidentally related to ARC. There is a proliferation of home grown singleton implementations (many of which unnecessarily override retain and release).

These should all be replaced with the following:

+ (MyClass *)singleton
{
    static MyClass *sharedMyClass = nil;
    static dispatch_once_t once = 0;
    dispatch_once(&once, ^{sharedMyClass = [[self alloc] init];});
    return sharedMyClass;
}

Every now and then you need the ability to destroy a singleton.
If you are using this for anything but UnitTests, you probably should not be using a singleton.

// declare the static variable outside of the singleton method
static MyClass *__sharedMyClass = nil;

+ (MyClass *)singleton
{
    static dispatch_once_t once = 0;
    dispatch_once(&once, ^{__sharedMyClass = [[self alloc] init];});
    return __sharedMyClass;
}

// For use by test frameworks only!
- (void)destroyAndRecreateSingleton
{
    __sharedMyClass = [[self alloc] init];
}


the fine print:
aboutarchive@amattn
© matt nunogawa 2010 - 2014
back ⬆