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

时间:2009-05-09 21:59:16

标签: objective-c cocoa macos core-data

我正在搞乱Core Data,我确信我错过了一些明显的东西,因为我找不到一个完全类似于我想要做的例子。

假设我正在玩DVD数据库。我有两个实体。电影(标题,年份,评级和与演员的关系)和演员(姓名,性别,图片)。

轻松获取所有电影。它只是:

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'),那么什么是“给我所有电影主演的谓词格式”[对象ID 1 - '查克诺里斯']“?

2 个答案:

答案 0 :(得分:6)

假设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中做同样的事情。

答案 1 :(得分:5)

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

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;