首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何通过关系进行核心数据查询?

如何通过关系进行核心数据查询?
EN

Stack Overflow用户
提问于 2009-05-09 21:59:16
回答 2查看 9.3K关注 0票数 8

我在摆弄核心数据,我确信我遗漏了一些明显的东西,因为我找不到一个与我想要做的事情完全相似的例子。

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

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

代码语言:javascript
复制
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Winery"
inManagedObjectContext:self.managedObjectContext];

获取标题中包含"Kill“的所有电影很简单,我只需添加一个NSPredicate:

代码语言:javascript
复制
NSPredicate *predicate = [NSPredicate predicateWithFormat:
@"name LIKE[c] "*\"Kill\"*""];

但是核心数据似乎抽象出了托管对象的id字段……那么,如何查询作为对象的属性(或:查询关系)?

换句话说,假设我已经有了我关心的Actor对象(例如,对象id 1- 'Chuck Norris‘),那么“给我所有的电影主演对象id 1- 'Chuck Norris'”的谓词格式是什么?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2009-05-09 23:10:43

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

代码语言:javascript
复制
// 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中使用访问器方法也可以做同样的事情。

票数 6
EN

Stack Overflow用户

发布于 2012-01-13 17:11:04

或者,您可以使用另一个谓词:

代码语言:javascript
复制
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Actor" inManagedObjectContext:self.managedObjectContext];

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name = %@",@"Chuck Norris"]
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:entity];
[request setPredicate:predicate];

YourActorObject *chuck = [[self.managedObjectContext executeFetchRequest:request error:nil] objectAtIndex:0];
[request release];

NSSet *moviesWithChuck = chuck.movies;
票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/844162

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档