Latest Tweets:

Concurrent programming with Core Data

Core Data is powerful and when harnessed correctly, it can transform your app into an ultra responsive, easy to maintain, scalable, background data consumer gem.

Unfortunately, it’s notoriously hard to master, especially when working with multiple threads, in which case, there are many possible issue that may arise, like UI blocking, deadlocks, data concurrency conflicts and many others. This article describes a technique that aims to solve these problems.

The pattern recommended by Apple for concurrent programming with Core Data is thread confinement: each thread must have its own entirely private managed object context.

Having just the main thread and its corresponding UI context is certainly not going to cut it: every time you make a time consuming persistent operation the UI will freeze. That’s certainly not what you want for your awesome app.

Using two threads, each with its context, may seem like the easy way out, but has one major flaw, complex fetching (or faulting) will always block the UI thread, no matter how we set the hierarchy between the two (siblings or parent-child).

Instead, consider this design:

  • Have a root context which runs on a low priority thread and saves its changes directly to the persistent store.

  • Keep the UI context as the root’s child, this way, when saved, it will push its changes to the root context, not the persistent store. This means that saving will be really fast (in memory). Also, complex fetches can be pre-fetched in the root or a slave context. All these leaves the UI context really light and fast.

  • Use multiple slave contexts as children of the root context. Every time one gets saved, it pushes the changes to the root context and then notifies and merge the changes into the UI context. This makes a save very cheap since all the changes are propagated in memory. The slave context usually does the heavy lifting, from huge and complex fetches to data importing, every time an expensive operations is done, this grunt will handle it.

Below you have a diagram that puts in perspective the relations between the UI, root and slave contexts.

Here’s a class that handles the initial setup. Also, below there’s a background fetch example. Inserting or updating works in a similar fashion.

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{

    //spawn a slave
    //you will typically have a singleton from which
    //you can access the master (in this example SPM)
    NSManagedObjectContext* slave = [SPM.localMaster spawnSlave];
    NSManagedObjectContext* ui = SPM.localMaster.uiMOC;
    __weak typeof(slave) weakSlave = slave;
    __weak typeof(ui) weakUi = ui;

    __block NSArray* resultIDs;

    //perform the fetch on the slave's thread
    [slave performBlockAndWait:^{
         NSFetchRequest *request=[[NSFetchRequest alloc] initWithEntityName:@"Entity"];
         request.predicate=[NSPredicate predicateWithFormat:@"Complex fetch predicate"];
         request.resultType = NSManagedObjectIDResultType;

         NSError *error;
         resultIDs = [weakSlave executeFetchRequest:request error:&error];
         //check the error
    }];

    [ui performBlock:^{
         //do something on the main thread with the results
         NSManagedObject* firstObject = [weakUi objectWithID:[resultIDs firstObject]];
    }];
});

What is NSValueTransformer and when should you use it?

NSValueTransformer does exactly what its name suggests, takes a value of any kind and transforms it into another one, think of it as a function encapsulated within an object.

Ok, so, all grand, but how does it help you? Over the years I’ve found that one of the most appropriate use case for NSValueTransformer is transforming data from an ill-defined form into a canonical form.

Think of the following scenario. You have to connect to a series of web services which return basically the same information, let’s say weather information, however, in different formats, some are maybe using JSON, others XML. Moreover, even for the ones that return the data in the same format, the structure, keys or values (e.g. temperature could be expressed in either °C or °F) differs.

A good design to solve this problem should, at least, allow you to add new services easily and not mix your business logic with the service data parsing and extracting.

Here is where NSValueTransformer comes really handy. You could have different NSValueTransformer subclasses for each service, transforming the received http NSData into a canonical NSDictionary or a custom class that could be used throughout your app. This gives you the possibility to add new services just by creating a new NSValueTransformer subclass that knows how to make this conversion happen. Below there’s an example on how one of this NSValueTransformer subclass implementation might look like.

+ (Class)transformedValueClass {
    return NSDictionary.class;
}

+ (BOOL)allowsReverseTransformation {
    return NO;
}

- (id)transformedValue:(NSData*)data {

    //the respones might not be what we're expecting,
    //so we're interested in the error, if any
    NSError* error;

    //we assume this service response is JSON
    NSMutableDictionary* response = 
[NSJSONSerialization JSONObjectWithData:data 
options:NSJSONReadingMutableContainers|NSJSONReadingMutableLeaves
error:&error];

    //we let others know if the transform ended with an error
    //and return right away if it did
    self.error = error;
    if (self.error) return nil;


    //our canonical response
    NSMutableDictionary* canonicalResponse = [NSMutableDictionary dictionary];

    //we copy the values we're interested in into the canonical dictionary
    //using the appropiate keys and transforming values where needed
    canonicalResponse[@"temperature"] = [self fahrenheitToCelsius:response[@"temp"]];
    canonicalResponse[@"location"] = [response[@"area"] capitalizedString];

    //and so on
    //...


    //the returned dictionary has a consistent
    //structure for each and every service now
    return canonicalResponse;
}

There you go, this little gem just saved you from a lot of tangled ifs and cases.

A category for positioning UIView with ease.

Let’s take the code below:

CGRect rect = button.frame;
rect.origin.x = tableView.frame.origin.x;
rect.origin.y = tableView.frame.origin.y + tableView.frame.size.height;
button.frame = rect;

Assuming button and tableView are in the same superview, the code aligns button just below tableView and to the left. That’s grand, but there’s a lot of boilerplate code around and if you’re not using nib files, you’ll be writing a lot of code like this. Actually, even if you do use nib files you’ll probably going to write this stuff often enough to become a nuisance.

Read More

sizeof(char) is always 1 but should be considered good practice

I stumbled upon this post today, and while the author did some very good remarks:

char i;
size_t iSize = sizeof i;

it’s easier to maintain and read than:

char i;
size_t iSize = sizeof(char);

I’m outraged sadden by his belief that since sizeof(char) (or sizeof i in our first example) is always 1 as per C standard we should always write code like this:

aChar = malloc(kCharsCount);

instead of:

aChar = malloc(kCharsCount*sizeof(*aChar));
//aChar = malloc(kCharsCount*sizeof(char)); as he puts it

Because, “It adds clutter and it suggests that you don’t know enough C”. That’s utterly rubbish.

Read More

*2

How to set breakpoints for specific functions/methods using LLDB command line

The motivation

Let’s say that during debugging you want to pause execution every time a view will appear in an iOS app (viewWillAppear) and you have so many controllers that adding the breakpoints manually would be cumbersome.

Read More

A simple way to set up GLKView without the Xcode template

The motivation

Xcode’s OpenGL Game template is not quite the cleanest way to start your OpenGL project. It adds a lot of code you don’t initially need and by the time you will need it, you’ll probably structure it in a different manner, which means you’ll have to clean it form the template.

The good news is that, to set up the most basic GLKView to handle your drawing routines you only need 3 lines of code.

The example project for this article can be found here

Read More

Advanced delegation. A decorator design pattern example.

The motivation

You probably wrote the following lines in your view controllers plenty of times:

self.tableView.delegate = self;
self.tableView.dataSource = self;

Usually, that’s fine.

However, if you have another table view in your app which has more or less the same look and feel, but a different controller managing it, a problem rises.

It would be nice to reuse all the delegation code you wrote in your initial controller. And only change the data and do other small customisations. You could tackle this problem in several ways.

But before we start, know that you can find the Github project for this article here.

Read More