Tag Archives: development

NSFetchedResultsController and iCloud

This took me a while to figure out so I thought it was worth blogging about. The short version: I’m using Core Data with iCloud syncing and it works… mostly. When starting up for the first time — when there is already data in iCloud —  none of the data appears in a table view, but restarting the app correctly displays it.

I know what you’re thinking: you’re not merging the updates into the right managed object context. Nope. Sorry. Thinking that was the problem is probably why it took me quite so long to track the real problem down!

So, what does the problem look like?

I set up my Core Data stack in the app delegate. Part of that includes connecting to iCloud:

    NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"XXX.sqlite"];
    NSDictionary *options = @{
                              NSMigratePersistentStoresAutomaticallyOption: @YES,
                              NSInferMappingModelAutomaticallyOption: @YES,
                              NSPersistentStoreUbiquitousContentNameKey : @"XXX"
                              };
    NSError *error = nil;
    _persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
    if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType
                                                   configuration:nil
                                                             URL:storeURL
                                                         options:options
                                                           error:&error]) {

The app delegate passes the managed object context through to the main view controller which then uses it to create a NSFetchedResultsController:

    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    // Edit the entity name as appropriate.
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"XXX" inManagedObjectContext:self.managedObjectContext];
    [fetchRequest setEntity:entity];
    // Set the batch size to a suitable number.
    [fetchRequest setFetchBatchSize:20];
    // Edit the sort key as appropriate.
    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"someTimestamp" ascending:NO];
    NSArray *sortDescriptors = @[sortDescriptor];
    [fetchRequest setSortDescriptors:sortDescriptors];
    // Edit the section name key path and cache name if appropriate.
    // nil for section name key path means "no sections".
    NSFetchedResultsController *aFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest
                                                                                                managedObjectContext:self.managedObjectContext
                                                                                                  sectionNameKeyPath:nil
                                                                                                           cacheName:@"Master"];
    aFetchedResultsController.delegate = self;
    self.fetchedResultsController = aFetchedResultsController;
	NSError *error = nil;
	if (![self.fetchedResultsController performFetch:&error]) {
        // Replace this implementation with code to handle the error appropriately.
        // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
	    NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
	    abort();
	}

(Again, this is pretty much Apple-standard boilerplate code —  nothing clever going on here.)

But what I found was that when there was already data in iCloud, the records did not automatically appear in the main view controller.

Eventually I found that this was not a threading issue — merging the changes into one context and trying to read them from another — by adding an explicit fetch request on a “debug” button. Doing this I could see the new data, even though the fetched result controller could not.

In my app delegate I listened for a number of notifications: NSPersistentStoreDidImportUbiquitousContentChangesNotification and NSPersistentStoreCoordinatorStoresWillChangeNotification. My expectation was that NSPersistentStoreCoordinatorStoresWillChangeNotification would fire before switching from the fallback store to the “real” one and NSPersistentStoreDidImportUbiquitousContentChangesNotification would fire when the new data was available.

I was half right. NSPersistentStoreCoordinatorStoresWillChangeNotification fired on a background thread, so I used GCD to ping it onto the main thread and reset the context.

But NSPersistentStoreDidImportUbiquitousContentChangesNotification didn’t fire at all. I guess the objects didn’t change as such, they just became available, which feels like a slightly false distinction to me.

So my next guess was to fire the fetch request again. The data was visible in the main threads context so surely this would find the data?

Nope. (And don’t call me Shirley.)

I was getting pretty lost at this point so I ended up just semi-randomly stopping the code and looking around in the debugger.

And, long story short, I realised that fetch requests have a reference to the persistent store in them — check out the affectedStores method. This meant that the NSFetchedResultsController was happily, and correctly, reporting on the empty and no longer used fallback store and completely ignoring the new and fully populated iCloud store.

The simple solution was to listen for the NSPersistentStoreCoordinatorStoresDidChangeNotification and create a completely new fetch request.

- (void)storesDidChange:(NSNotification*)notification {
    self.fetchedResultsController = nil;
    [NSFetchedResultsController deleteCacheWithName:@"Master"];
    [self.tableView reloadData];
}

(I did think of just adding the new persistent store to the old fetch request but I wasn’t sure that this would create the refresh anyway and, given the frequency with which this is likely to happen, I thought it would be cleaner just to start from scratch.)

These weird problems almost always boil down to just a couple of lines of code. This time was no exception.

What to do?

There have been a few blogs recently about people finding their true vocation and discovering that it’s not developing software. This is not a “me too” post. I do still develop software for a living and I don’t intend becoming a writer or anything else any time soon. But like most people (I assume) my career has taken turns that I never would have imagined when I started out.

In fact when I was at school I took quite some time trying very hard not to be a software developer for a living. I took geography rather than the rather more obvious (if you know me) chemistry because I wanted to be a pilot. I was so determined to keep programming computers as a hobby that I almost took woodwork instead of computer studies when I was fourteen.

Even when I went to university a few years later I tried (and failed) to read maths. After graduating with a Computer Science degree I fell into a job in software in many ways because I wasn’t sure what else to do.

If this sounds negative it’s because that’s what I was thinking at the time. With hindsight I’m glad that all the effort I spent avoiding my current career didn’t pay off.

The job I took turned out to be a lucky break in some respects. It was at a medium sized consulting company which allowed me to work in lots of different positions on lots of different projects in a relatively short period of time. The effect of this was that I was able to mentally break up the job “Software Developer” into aspects that previously I would have conflated.

What I learned is that I enjoy creating stuff more than managing people. That I’m better at sketching designs on a white-board than I am at testing the resulting code. That I like to make things that are useful rather than just architecturally beautiful. And that I like working with end users, even when they ask for the impossible or contradictory things. (Okay, not exactly at the time they request it but you get the idea.)

In practice this means that I seek out roles that are broader than a stereotypical developer1 and certainly require more than just coding. Hard-core developers may sneer at the fact that the most common job title I’ve had over the years is some variation on “Consultant” but I actually quite like that it means very little. Under the same title I’ve done everything from development to pre-sales consulting to business analysis.

The point, of course, is not that this is The Right career, only that considering “development” as a single activity wasn’t a helpful way of thinking about what I wanted to do. By breaking down the role into its constituent parts I’ve been able to get a balance of variety and control that I’m happy with most of the time.

Put another way, I’ve been functionally decomposing my career and optimising it for years. I guess I really am a developer at heart.

  1. I think it’s fair to say that the responsibilities of a “developer” vary more from job to job than that of, say, “accountant.” []

Familiarity Breeds Contempt

This week I did a presentation at the London iPhone Developer Group meeting. Given my experience with using lots of APIs, I thought it might be a good, if dry, topic. I tried to spice it up by complaining about lots of them and trying to condense that negativity into some useful lessons to take away.

Most of the other discussions of this subject that I’ve seen focus on designing libraries but I thought the same lessons could be applied to all kinds of interfaces, from Objective C libraries to REST API’s for connecting to web services. (I don’t mean to suggest that the focus of the two articles I link to is wrong. They’re both very much worth reading.)

You can see a PDF of the slides here (though they might not make much sense without what I was saying at the time), but the gist is as follows:

  • Design your APIs around use-cases. Many appear to be designed around “how can I made the data I have available.” This is the wrong way round
  • Clients need to access data in a predictable, reliable way. Being clever accepting any old junk and trying to do the right thing is often not the right thing to do
  • Communicate how it works and how it’s going to change clearly. Examples and sample code are always useful
  • Think about error cases. “Something went wrong” is not a good error message
  • Think about the devices that people are likely to be accessing your service from. Mobile apps have latency, bandwidth and CPU constraints that desktop computers and other servers do not. The iPad 4 has more resources to throw at a problem than an iPhone 3GS. Your code might need to work on both
  • Be consistent. Make your API look like other, similar APIs and use the patterns of the technology you’re using. That means delegates and return codes for Objective C, inheritance and exceptions for C#
  • And, most importantly, use your own API. Don’t keep special “secret sauce” for your self. How else are you going to know whether it works than by actually using it?

Ideally I’d end a presentation (or blog post) with salient advice on the best way to do something. This is an exception. I don’t think there’s a one-size-fits-all solution and I’m generally weary of Best Practice guides.

So I’ll end by noting that poor APIs result in poor applications. It’s worth investing the time and energy in doing it well. Your users and your future self will thank you.

My delicious.com bookmarks for March 13th through March 14th

My delicious.com bookmarks for February 8th through February 20th

  • An Attribution Failure Theory – "Credit is easy. Well, mostly easy. It might have been hard to get the format of citations right at first in school when we were writing papers, but the act of citing is easy. You just do it. Yet, people all over the Internet don’t."
  • You Are Not Ruthless Enough – "Here’s the thing: you are not ruthless enough. You are certainly not ruthless enough to your objects, and you probably need to be more ruthless to yourself." Programming Is Hard, Part 381.
  • You Will Never Kill Piracy, and Piracy Will Never Kill You – "The seven step, ten minute download process (which will be about ten seconds when US internet speeds catch up with the rest of the world) is the real enemy the studios should be trying to tackle."

My delicious.com bookmarks for January 10th through January 30th