Multithreaded Coredata save in Lion
Multithreaded Coredata save in Lion
- Subject: Multithreaded Coredata save in Lion
- From: Jim Thomason <email@hidden>
- Date: Sun, 31 Jul 2011 10:58:02 -0500
Gang,
I've encountered an odd bug/issue/feature(?) in Lion and want to know
if there's a workaround available.
I have a multithreaded CoreData application. It does a lot of
calculations on the context, so it spawns off a separate thread and
creates a new ManagedObjectContext to do its work. AFAIK, I'm
following proper Best Practices for multi-threaded core data access.
This all works fine.
The issue is, at the start of my thread, I call saveDocument: on the
main context, in the main thread via this:
[self performSelectorOnMainThread:@selector(saveDocument:)
withObject:nil waitUntilDone:YES];
I didn't want to worry about jumping through the hoops of merging the
contexts, so I just ensure the main context is clean and saved. It
invokes saveDocument, then checks to see if the context still has
changes, and if it does it bombs out and refuses to continue, assuming
that the save failed for some reason.
This works fine under Snow Leopard (and Leopard, and it used to work
under Tiger as well, though I no longer support that OS). But under
Lion, it fails since it doesn't actually wait until the save is
complete. It looks like pre-Lion, saveDocument: would directly invoke
the writeToURL:... method, whereas in Lion it's deferring it until the
next invocation of the run loop.
So under Snow Leopard, I'd see this behavior:
SECOND THREAD: perform saveDocument on Main, wait until done
MAIN THREAD: call saveDocument
MAIN THREAD: call writeToURL:...
SECOND THREAD: done waiting for main to complete, carry on.
But now on Lion, I see this:
SECOND THREAD: perform saveDocument on Main, wait until done
MAIN THREAD: call saveDocument
SECOND THREAD: done waiting for main to complete, carry on. Sees that
the main MOC still has changes, fails out.
MAIN THREAD: call writeToURL:...
So Lion waits for saveDocument: to finish, but then writeToURL:... is
called later. I have a simple test case to verify:
http://www.prototypesite.net/threadedsavetest.zip
If you run it on Lion, writeToURL is called after the second thread is
done waiting. If you run it on Snow Leopard, it's done before.
Is this a bug or a feature? If it's a feature and expected to behave
this way, then what's the proper way for me to get this behavior now,
in a way that's backwards compatible on Snow Leopard and Leopard?
-Jim....
_______________________________________________
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