I get runtime errors which seem to result from my incorrect implementation of GCD
in combination with my custom NSManagedObjects.
Nested in a GCD
First,
"how to pass the correct managed object context down to my custom NSManagedObjects."
We create NSManagedObject
with NSManagedObjectContext
. not the other way around. So, when you have a NSManagedObject
, you can access the NSManagedObjectContext
by asking its property: – managedObjectContext
as listed in Apple Document
Second,
When working with CoreData, multi-threading could be a little tricky. especially for the beginner. The are all kind of details that you need to take care of.
I highly recommend you checkout the Parent-Child NSManagedContext
. then, using MagicRecord.
By using MagicRecord, you can simply Grand Central Dispatch with a Block like this:
[MagicalRecord saveInBackgroundWithBlock:^(NSManagedObjectContext *localContext){
// here use the `localContext` as your NSManagedContext and do things in the background.
// it will take care of all the rest.
}];
If you need to pass NSManagedObject
into this block, remember to only pass the NSManagedObjectID
instead of the proprety.
this is a example.
NSManagedObjectID *coaMapID = CoaMap.objectID;
[MagicalRecord saveInBackgroundWithBlock:^(NSManagedObjectContext *localContext){
coaMap *aCoaMap = (coaMap *)[localContext existingObjectWithID:coaMapID error:&error];
// then use aCoaMap normally.
}];
Hope this helped.