Blog

Headnix — Clip It!

Thursday, Sep 02, 2010 Cocoa Binding and Core Data in multi-threading environment

There are several great articles covering how to use Core Data in multi-threading environment.

The scenario involves a background thread making changes to its own managed object context. The main thread (UI thread) should show changes made by the background thread to the background thread’s managed object context.

Core Data allows a managed object context to post notification about its changes. Listen to “NSManagedObjectContextObjectsDidChangeNotification” posted by the background thread’s managed object context. To merge the changes from another context to the target context, use “mergeChangesFromContextDidSaveNotification”.

However, even changes from the background thread’s managed object context are merged by using mergeChangesFromContextDidSaveNotification method. The user interface does not show the new values of those changed managed object. (this happens to managed objects which are updated)

The reason is that the main thread’s managed object context caches data retrieved from persistent data store. It will not fetch the updated value from the database as long as MOC finds a cache copy of the managed object. This renders refreshObject method useless.

To solve this problem, set the staleness interval to 0.0 (default is -1.0) which essentially means the MOC should always look up the data store for managed object data in case of fault, no more cache lookup.

Sample code attached: ThreadedCoreData

If you are looking for Finger iPhone app, please go to Finger's site.

Copyright © 2007 Headnix. All rights reserved. Design by BeansBox.