iOS /核心数据实体与预定义数据的关系

时间:2015-09-17 05:32:17

标签: ios objective-c core-data

我有两个Objective-C核心数据实体 - 比如人和国籍。人与国籍有一个To-One关系,而国籍与Person有To-Many关系。此外,Person类可以具有任意数量的对象/行,而国籍将具有200个奇数实例的预定义列表。因此除了那200件物品外,人不应该为自己分配国籍。

有人可以建议我们如何编写代码或者有可用的示例代码?害怕我似乎无法开始如何利用setValue:forKey:here ...

非常感谢!

1 个答案:

答案 0 :(得分:1)

我们假设您的国籍实体具有唯一标识该国籍的“名称”属性。您可以提供任何方式的UI来从用户处获取此信息。它可以输入一个字符串或获取所有国籍,并将它们放在一张桌子或某种选择器中。

如果你想要所有国籍,那很容易。

NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"Nationality"];
NSError *error;
NSArray *nationalities = [moc executeFetchRequest:fetchRequest error:&error];
if (nationalities == nil) {
    // handle error
} else {
    // You now have an array of all Nationality entities that can be used
    // in some UI element to allow a specific one to be picked
}

如果你想根据名字的字符串查找它......

NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"Nationality"];
fetchRequest.predicate = [NSPredicate predicateWithFormat:@"name = %@", nationalityName];
fetchRequest.fetchLimit = 1;
NSArray *nationalities = [moc executeFetchRequest:fetchRequest error:&error];
if (nationalities == nil) {
    // handle error
} else {
    NSManagedObject *nationality = [nationalities firstObject];
    // If non-nil, it will be the nationality object you desire
}

创造这个人并指定其国籍也是直截了当的......

if (nationality) {
    NSManagedObject *person = [NSEntityDescription insertNewObjectForEntityForName:@"Person" inManagedObjectContext:moc];
    // Set any attributes of the Person entity
    [person setValue:@"Fred Flintstone" forKey:@"name"];

    // Assign its nationality, and as long as the relationship is setup with
    // inverse relationships, the inverse will be automatically assigned
    [person setValue:nationality forKey:@"nationality"];
}