Monday, June 24, 2013

iOS 5 NSFetchedResultsController Sorting Issues With RestKit

We were having issues with NSManagedObjects not being sorted correctly after modifying managed objects locally and saving, but we didn't know why so I had to do some research. I found this post: http://wbyoung.tumblr.com/post/27851725562/core-data-growing-pains which was helpful, and the code snippet below was what fixed it. The issue in iOS 5 is that the NSFetchedResultsController deadlocks when there are changes in a child context. So with RestKit on that particular view controller we just had to switch from using the mainQueueManagedObjectContext to mainQueueManagedObjectContext.parentContext for iOS 5 and it resolved all of our issues.
#define SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(v)  ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedAscending)


  NSManagedObjectContext *newManagedObjectContext;
  if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"6.0")) {
    newManagedObjectContext = [RKObjectManager sharedManager].managedObjectStore.mainQueueManagedObjectContext;
  } else{
    newManagedObjectContext = [RKObjectManager sharedManager].managedObjectStore.mainQueueManagedObjectContext.parentContext;
  }
  NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"Entity"];
  NSFetchedResultsController *newFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:newManagedObjectContext sectionNameKeyPath:nil cacheName:nil];