一个非常简单的问题,我找不到答案。我将我的Core Data实体分为子类-Area
和GPS
,并使用JSON文件中的数据进行设置。好像很好但是,如何设置两个新创建的Entity对象之间的关系?
NSManagedObjectContext *context = [self managedObjectContext];
Area *area = [NSEntityDescription
insertNewObjectForEntityForName:@"Area"
inManagedObjectContext:context];
GPS *gps = [NSEntityDescription
insertNewObjectForEntityForName:@"GPS"
inManagedObjectContext:context];
NSDictionary *attributes = [[area entity] attributesByName];
for (NSString *attribute in attributes) {
for (NSDictionary * tempDict in jsonDict) {
id value = [tempDict objectForKey:attribute];
if ([value isEqual:[NSNull null]]) {
continue;
}
if ([attribute isEqualToString:@"latitude"] || [attribute isEqualToString:@"longtitude"]) {
[gps setValue:value forKey:attribute];
}
else {
[area setValue:value forKey:attribute];
}
}
[area setAreaGPS:gps]; // Set up the relationship
}
从
Area
到GPS
的关系的名称是areaGPS
错误:
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Unacceptable type of value for to-many relationship: property = "areaGPS"; desired type = NSSet; given type = GPS; value = <GPS: 0x369540>
我已经在几个示例中看到了
[area setAreaGPS:gps];
的这种语法,但显然我不理解如何正确使用它。
最佳答案
您已将关系设置为一对多关系。根据您定义区域的方式,这可能是,也可能不是。如果一个区域可以有多个与之关联的GPS对象,那么您就很好。然后,您只需要将[area setAreaGPS:gps]
更改为:
NSMutableSet *mutableGPS = [area.areaGPS mutableCopy];
[mutableGPS addObject:gps];
[area setAreaGPS:mutableGPS];
如果只想将一个GPS对象与一个Area对象相关联,则必须将关系更改为不是一对多关系,而是一对一关系。在这种情况下,您不需要更改任何代码(除了重新生成
NSManagedObject
子类)。
关于ios - 设置两个新创建的Core Data对象的关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14309404/