我在摆弄核心数据,我确信我遗漏了一些明显的东西,因为我找不到一个与我想要做的事情完全相似的例子。
假设我正在使用一个DVD数据库。我有两个实体。电影(片名、年份、评级以及与演员的关系)和演员(姓名、性别、图片)。
获取所有的电影是很容易的。它只是:
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Winery"
inManagedObjectContext:self.managedObjectContext];获取标题中包含"Kill“的所有电影很简单,我只需添加一个NSPredicate:
NSPredicate *predicate = [NSPredicate predicateWithFormat:
@"name LIKE[c] "*\"Kill\"*""];但是核心数据似乎抽象出了托管对象的id字段……那么,如何查询作为对象的属性(或:查询关系)?
换句话说,假设我已经有了我关心的Actor对象(例如,对象id 1- 'Chuck Norris‘),那么“给我所有的电影主演对象id 1- 'Chuck Norris'”的谓词格式是什么?
发布于 2009-05-09 23:10:43
假设Actor和Movie实体之间存在一对多的反向关系,您可以像获取任何特定实体一样获取Chuck Norris的实体,然后访问附加到Actor实体上的关系的Movie实体数组。
// 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中使用访问器方法也可以做同样的事情。
发布于 2012-01-13 17:11:04
或者,您可以使用另一个谓词:
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;https://stackoverflow.com/questions/844162
复制相似问题