Passing errors across threads using blocks

In these strange times of blocks and concurrency-patterned managed-object-contexts (I swear I saw one once, but it flew off before I could grab my camera), it’s not uncommon to be calling methods across thread boundaries and needing to return an error object as a result. Here’s a simple example:

So what’s wrong here? If saving fails, it will return by reference an NSError object encapsulating why, stored into the error pointer. In all likelihood, that error is autoreleased, due to be deallocated when the current pool drains. When will it drain? Well, potentially, -performBlockAndWait: runs on a different thread to the caller. And if so, that will likely drain the autorelease pool when that chunk of work completes. Quite possibly before the caller of our code is finished dealing with the error!

Normally blocks retain objects as needed for you, but because the error is passed around by reference, we have no such luxury. Instead, here’s the solution:

This ensures that the error object is kept alive for as long as the calling thread needs it.

© Mike Abdullah 2007-2015