NSManagedObjects and crossing threads

Nobody likes ‘Statement still active’ errors

Greg Gunner
Mar 29, 2014 · 1 min read

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)

    Written by

    Product Person

    Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
    Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
    Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade