我有两个 Objective-C 核心数据实体——比如 Person 和 Nationality。 Person 与 Nationality 具有一对一关系,而 Nationality 与 Person 具有一对多关系。此外,Person 类可以有任意数量的对象/行,而 Nationality 将有一个包含 200 个奇数实例的预定义列表。所以除了这 200 个对象之外,Person 应该不能为自己分配国籍。
有人可以建议我们如何编写代码,或者如果有可用的示例代码?恐怕我似乎无法开始了解如何利用 setValue: forKey: here...
非常感谢!
Best Answer-推荐答案 strong>
假设您的国籍实体具有唯一标识该国籍的“名称”属性。您可以提供任何方式的 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"erson" 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"];
}
关于iOS/Core Data 实体与预定义数据的关系,我们在Stack Overflow上找到一个类似的问题:
https://stackoverflow.com/questions/32623173/
|