这可能是一个非常原始的问题。我有一份属于不同国家的州名单。
Data 1: state - xyz
country - A
Data 2 : state - abc
country - B
Data 3: state - ght
country - A
Data 2 : state - ase
country - B
在核心数据中,我有不同的州和国家实体。在保存时如何将所有状态放入其国家/地区对象中?
编辑:国家/地区关系
答案 0 :(得分:1)
假设数据是字典数组,
for (NSDictionary *data in datas) {
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Country" inManagedObjectContext:[dbManager getCurrentContext]];
[fetchRequest setEntity:entity];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name = %@", [data valueForKey:@"country"]];
[fetchRequest setPredicate:predicate];
NSError *error;
NSArray * fetchedObjects = [managedObjectContext executeFetchRequest:fetchRequest error:&error];
if ([fetchedObjects count] > 0) {
Country *country = [fetchedObjects objectAtIndex:0];
//Using CoreDataGeneratedAccessors
[country addStateObject:[data valueForKey:@"state"]];
} else {
Country *country = [NSEntityDescription insertNewObjectForEntityForName:@"Country" inManagedObjectContext:managedObjectContext];
country.name = [data valueForKey:@"country"];
...
if ([managedObjectContext save:&error])
{
//Using CoreDataGeneratedAccessors
[country addStateObject:[data valueForKey:@"state"]];
}
}
}
希望这可以帮到你