ARC Welding

Now this would make a good interview question: Why does this snippet crash at runtime?

The answer is, because ARC is not welded to Core Foundation types as well as one might assume:

What could be releasing objects automatically? ARC – that’s its job. From ARC’s point of view, the UIColor created with -colorWithRed:… was used to access the CGColor, and then is no longer needed. The UIColor wasn’t assigned to anything, therefore ARC decided that the object could be cleaned up at the semicolon at the end of the expression. Therefore it’s a candidate for disposal and got released. The disassembly, viewable in Xcode with Product->Generate Output->Generate Assembly file, shows that this is the case…

If you saw that one coming, congratulations; like most people probably, we’d kinda assumed that objects like that would have autoreleasepool behaviour. But not so! For discussion of various ways around this problem and its ilk, check out discussion at

ARC Gotcha – Unexpectedly Short Lifetimes

A funny thing happened on the way to the ARC

If you’re in a hurry, the simple takeaway is to use the .CGColor accessor only at the place it’s actually passed to something.

Alex | February 28, 2012

Leave a Reply