Re: NSManagedObjectContextDidSaveNotification across MOCs on two threads
Re: NSManagedObjectContextDidSaveNotification across MOCs on two threads
- Subject: Re: NSManagedObjectContextDidSaveNotification across MOCs on two threads
- From: Roland King <email@hidden>
- Date: Thu, 16 Sep 2010 21:44:16 +0800
On 16-Sep-2010, at 12:01 AM, Jerry Krinock wrote:
>
> On 2010 Sep 15, at 07:02, Roland King wrote:
>
>> Checking the documentation for NSNotificationCenter however I see that the notifications are processed in the thread in which they were sent, that of course will be my indexing thread and that's exactly what I was trying to avoid, updating contexts across threads. What's the best way to deal with this?
>
> Not sure what's the best way, but I've used one of the performSelectorOnMainThread… methods to make a notification get posted on the main thread.
>
What I did in the end was this. My NSManagedObjectContext (MOC) is vended from a helper object so I made that thread-aware, it vends a thread-specific MOC given the thread on which it's called, if there isn't one, it makes one and puts it in a CFDictionary. This ensures that all the threads are using their own MOCs. To clean up the dictionary I listen for NSThreadWillExitNotification(s) and use that to remove the MOC from the dictionary.
I also listen for NSManagedObjectContextDidSaveNotification(s) and when I get one, I iterate the dictionary of Thread -> MOC and, for all the MOCs apart from the one which caused the notification, I execute mergeChangesFromContextDidSaveNotification: but I use performSelector:onThread: to queue up the merge on the thread pertaining to that MOC.
The whole thing took only a dozen lines of code and appears to be working well in my particular use case. I know that for instance I always want any saves to be reflected in any other thread's MOC at or around the point of saving and I know that any operation which starts modifying an MOC always runs in one thread, so I don't have the issue of having changes sprayed around different MOCs because my operation walked around different threads. With those constraints, this was a pretty easily coded solution to my threaded indexing issue without having to lock and unlock every MOC every time I used it. _______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden