Pointer to a Pointer

I came to a point (the irony…) where I needed the following:


// Declare the queue
dispatch_queue_t workingQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(workingQueue,
^{

NSError *parsingError = nil;

if (condition == YES)
{
    [self doSomethingLongWithError:&parsingError];
}
else
{
    [self doSomethingElseLongWithError:&parsingError];
}

dispatch_async(dispatch_get_main_queue(), ^{

// Check if we got an error

if (parsingError)
{
    error(parsingError);
}
else
{
    success();
}
});
});
}

So what’s happening?

– I have one working thread doing some heavy stuff (in this case parsing)
– Once that work is done I want to update my UIViewController, by executing the block success() or the block error(parsingError).

The idea here is to be able to actually do something heavy, not expecting a return, and also be able to know if something went wrong.

As you might imagine the signature of the methods is:

- (void)doSomethingLongWithError:(NSError **)error;
- (void)doSomethingElseLongWithError:(NSError **)error;

If you notice, I am passing an &parsingError in both methods. Why? Well that’s where it becomes interesting the use of pointers to pointers. The powerful aspect of it is that I am able to declare the parsingError on the scope of the working thread, pass it’s pointer to a different scope (in this case of the methods) and once that working thread is done I can rely on the value of the parsingError on the main thread to take the appropriate action.

Advertisements
Tagged , , , , , , ,

One thought on “Pointer to a Pointer

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: