Sunday, March 29, 2009

Core Data Mutlithreading

After some consideration I decided that updating indeed needed to be done on its own separate thread. I did a bit of reading on how its recommended to use two contexts if multiple threads need to access a common persistent store. So I made a small test app for the sake of experimentation.

In the app, I made 3000 simple managed objects and saved them. Afterwards, I started another thread to do updating on them, but with a different context. After the updating done, I enumerated over all the objects in the new context, got their object IDs and made the call:

[self performSelectorOnMainThread:@selector(updateMainContextWithObjectID:) 
                                  withObject:anID 
                             waitUntilDone:NO];

In the updateMainContextWithObjectID: method I did: 

NSManagedObject* changedObject = [originalContext objectWithID:anID];
[originalContext refreshObject:changedObject mergeChanges:NO];
[coreDataDelegate saveContext:originalContext];

This ended up actually locking down my app until all the objects were updated. What I ended up discovering was the waitUntilDone: part should be YES. This gave me a true multithreaded feel.

Moving along, I found that changing the updateCoreDataStore methods of each of the XML data controllers to be run on a separate thread was relatively painless. However, there is one curious problem I ran into that in all my google-ing, I haven't found an answer. How does one handle managed objects deleted in one context and still around in another? That's what I'm going to be pondering for tomorrow.

In the mean time, I wouldn't be surprised if my svn update actually ended up breaking things. It compiles and runs, but I'd question the accuracy of the data presented. Well, at least I can hide behind the excuse that this app is still in alpha for now.

2 comments:

  1. "How does one handle managed objects deleted in one context and still around in another?"

    You will want to look at the docs for NSManagedObjectContextDidSaveNotification.

    ReplyDelete
  2. Hey Mizuki!

    Just saw the screen cap of your mac version of evemon.

    looking good!
    :)


    good luck in using it for your college degree

    - oni

    ReplyDelete