gpt4 book ai didi

objective-c - 如何通过关系做Core Data查询?

转载 作者:太空狗 更新时间:2023-10-30 03:36:36 26 4
gpt4 key购买 nike

我正在处理核心数据,我确信我遗漏了一些明显的东西,因为我找不到一个与我正在尝试做的完全相似的例子。

假设我正在使用 DVD 数据库。我有两个实体。一部电影(片名、年份、评级以及与 Actor 的关系)和 Actor (姓名、性别、图片)。

获取所有电影很容易。这只是:

NSEntityDescription *entity = [NSEntityDescription entityForName:@"Winery"
inManagedObjectContext:self.managedObjectContext];

获取所有标题中带有“Kill”的电影很容易,我只需添加一个 NSPredicate:

NSPredicate *predicate = [NSPredicate predicateWithFormat:
@"name LIKE[c] "*\"Kill\"*""];

但 Core Data 似乎抽象出托管对象的 id 字段...那么我如何查询作为对象的属性(或:查询关系)?

换句话说,假设我已经有了我关心的 Actor 对象(例如 [Object id 1 - 'Chuck Norris']),“给我所有由 [Object id 1] 主演的电影的谓词格式是什么- '查克诺里斯']"?

最佳答案

假设 Actor 和 Movie 实体之间存在一对多的反向关系,您可以像获取任何特定实体一样获取 Chuck Norris 的实体,然后访问 Movie 实体数组附加到 Actor 实体上的关系。

// Obviously you should do proper error checking here... but for this example
// we'll assume that everything actually exists in the database and returns
// exactly what we expect.
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Actor" inManagedObjectContext:self.managedObjectContext];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name LIKE[c] 'Chuck Norris'"];
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:entity];
[request setPredicate:predicate];

// You need to have imported the interface for your actor entity somewhere
// before here...
NSError *error = nil;
YourActorObject *chuck = (YourActorObject*) [[self.managedObjectContext executeFetchRequest:request error:&error] objectAtIndex:0];

// Now just get the set as defined on your actor entity...
NSSet *moviesWithChuck = chuck.movies;

请注意,此示例显然假设 10.5 使用属性,但您可以使用访问器方法在 10.4 中执行相同的操作。

关于objective-c - 如何通过关系做Core Data查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/844162/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com