NSManagedObjects and crossing threads
Nobody likes ‘Statement still active’ errors
Anyone who has worked with Core Data will know that NSManagedObjects (or perhaps more accurately NSManagedObjectContexts) cannot cross threads.
This leads to you having to do some additional work; if you have some heavy processing to do on a load of NSManagedObjects (searching maybe) then you’ll be wanting to do that in a background thread.
However, should you try to then populate your UI based on those background fetched NSManagedObjects you’ll get all sorts of issues and probably your fair share of statement still active errors.
It’s not all bad news though.
Core Data is very fast at returning an NSManagedObject based on it’s objectID. So all you need to do is replace each of those background NSManagedObjects with their main thread equivalent using something like this:
1. Enter a background thread.
2. Fetch arrays of multiple NSManagedObject subclasses based on a search string.
3. Perform some operations on those results; sorting, grouping etc.
4. Return to the main thread.
5. Pass my results to moveManagedObjects: toContext:
6. Populate the UI.
[Apple’s Core Data Concurrency Documentation](https://developer.apple.com/Library/ios/documentation/Cocoa/Conceptual/CoreData/Articles/cdConcurrency.html)