I have a problem with core data when setting relationships:
The code below crashes randomly when setting the relationships between country and region.
If I disable the second for-loop, the method completes without errors.
Everything happens within the context living on the background-thread.
Again: I can create the objects for the regions and countries without trouble and they show up in the Simulators database just fine – but as soon as I try to set the relationships between then, the app crashes randomly.
Any thoughts ?
for (Region* region in regions) {
// only store if region code isn't empty
if (region.m_RegionCode != nil && [region.m_RegionCode length] > 0) {
NSManagedObject* cdRegion = [NSEntityDescription insertNewObjectForEntityForName:CDREGION inManagedObjectContext:self.objectContextBackground];
[cdRegion setValue:region.m_RegionCode forKey:@"code"];
[cdRegion setValue:region.m_regioncodedescription forKey:@"name"];
}
}
[self saveBackgroundContext];
for (Region* region in regions) {
if (region.m_RegionCode != nil && [region.m_RegionCode length] > 0) {
NSManagedObject* cdRegion = [self getManagedObject:CDREGION withCode:region.m_RegionCode];
NSManagedObject* CDCountry = [self getManagedObject:CDCOUNTRY withCode:region.m_countrycode];
[cdRegion setValue:CDCountry forKey:@"country"];
}
}
well – just to let you know: it actually was the problem (I know – it is listed on top of all pages regarding this topic 🙂 that I used a context between threads.
I mixed up queues and threads. I created a single background-queue where I used my “background-context” … but of course i created several threads within that, who where interacting with the context… so…
btw: it was this excellent article that finally clarified it for me:
(came right in time 🙂
http://www.cimgf.com/2011/08/22/importing-and-displaying-large-data-sets-in-core-data/