On Apr 24, 2009, at 6:24 PM, Daniel Child wrote:

I have a Core Data app that imports data via a separate managed object contexts. Without multithreading, the operation works fine. But since the import takes over a minute, I want to do the import in a different thread. The data consists of an archived table of data with records.

This is my first time attempting to use threads, and the basic problem I'm having is figuring out the best way to pass the complex object (the table of records) from one thread to another. Since there are something like 50,000 records, deep-copying would be ugly.

Indeed. Furthermore, since you're working with Core Data, you may not actually want those 50K objects passed from one thread to another; Core Data strongly prefers threads to work in entirely separate managed object contexts. If you use one NSManagedObjectContext per thread, but these contexts use the same NSPersistentStoreCoordinator, Core Data has just the solution for you.

This must be a common issue with multithreading. Is there an elegant way to get access to deeper layers of a complex object from within another thread? i.e. a way to make 2) or 3) above work?

In fact, you can probably get away with not passing the objects "across" to the main thread at all. Since your user interface will be "fed" from the managed object context you've created for the main thread — whether you're using bindings or doing your user interface manually — and you can set that context to use the same coordinator as your background thread, you can just do appropriate fetches and relationship traversals against the main thread's context to build up the object graph you're actually presenting to the user.

If you do want to still pass information from the background thread to the main thread, all you need to pass are the managed object IDs of the (saved) objects the main thread will be interested in. You can just use -[NSObject performSelectorOnMainThread:withObject:waitUntilDone:] for this and pass either individual object IDs or collections of them. Then on the main thread, you can ask the main thread's managed object context for the managed object with that ID, and it'll hand you back an appropriate one that you can use for your user interface.

  -- Chris

_______________________________________________

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

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:
http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com

Reply via email to