Tuesday, May 24, 2011

Core Data & Multi-Threading, part 1337

So i've made yet another Core Data Discovery, at this rate i might need to write a ebook. Now we all know that the golden rule of using Core Data with different threads is to not share contexts between threads.
So if you need to refer to an object on multiple threads you need to use it's NSManagedObjectID. Thats all well and good, but what if you need to call [NSManagedObjectContext save:] multiple times. Well in short it's gonna suck. Well thats cool you say, i can just use the id anyway ... Not quite. There are two types of ID's, permanent and temporary.
Now in my experience Core Data seems to get confused when you use temporary ID's to look up objects on another NSManagedObjectContext. So really to stop these conflicts we need to get a permanent id, but we need to obtain one of these ID's without saving the NSManagedObjectContext.


Well are you ready for the magic ... Shazam

[NSManagedObjectContext obtainPermanentIDsForObjects: error:]

This awesome method will take an array of managed objects, and give them permanent ID's. From my brief tests the overhead is minimal compared to the traditional save method.

Thats all i've got for today, keep on trucking.

[]'s 4 life

No comments: