我正在搞乱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 – ‘Chuck Norris的]“?
解决方法
假设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;