ios - 设置两个新创建的Core Data对象的关系

标签 ios xcode core-data

一个非常简单的问题,我找不到答案。我将我的Core Data实体分为子类-AreaGPS,并使用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
        }

AreaGPS的关系的名称是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/

相关文章:

ios - 应用安装失败 : The application bundle does not contain an executable in Swift Xcode

ios - 为什么我不能使用 mergDropbox 链接我的 Dropbox 应用程序?

ios - 显示pdf时是否可以在UIwebview中删除["Page 1 of 20" View ]?

objective-c - 我们不应该再@synthesize了吗?

ios - 如何在 Xcode 中将兼容设备设置为仅与 ARKit 兼容的设备?

ios - 核心数据 NSManagedObject 没有有效的 NSEntityDescription

ios - 在 Swift 中将开尔文转换为摄氏度

objective-c - 使所有文本显示在 UITableView 单元格中

ios - 另一个实体的核心数据过滤器

ios - 如何在运行时检查核心数据属性类型?