objective-c – 如何通过关系进行核心数据查询?

前端之家收集整理的这篇文章主要介绍了objective-c – 如何通过关系进行核心数据查询?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在搞乱Core Data,我确信我遗漏了一些明显的东西,因为我找不到一个完全类似于我想做的事情的例子.

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

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

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

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

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

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

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

解决方法

假设Actor和Movie实体之间存在一对多的反向关系,您可以像获取任何特定实体一样获取Chuck Norris的实体,然后访问附加到该实体的Movie实体数组. Actor实体上的关系.
  1. // ObvIoUsly you should do proper error checking here... but for this example
  2. // we'll assume that everything actually exists in the database and returns
  3. // exactly what we expect.
  4. NSEntityDescription *entity = [NSEntityDescription entityForName:@"Actor" inManagedObjectContext:self.managedObjectContext];
  5. NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name LIKE[c] 'Chuck Norris'"];
  6. NSFetchRequest *request = [[NSFetchRequest alloc] init];
  7. [request setEntity:entity];
  8. [request setPredicate:predicate];
  9.  
  10. // You need to have imported the interface for your actor entity somewhere
  11. // before here...
  12. NSError *error = nil;
  13. YourActorObject *chuck = (YourActorObject*) [[self.managedObjectContext executeFetchRequest:request error:&error] objectAtIndex:0];
  14.  
  15. // Now just get the set as defined on your actor entity...
  16. NSSet *moviesWithChuck = chuck.movies;

作为一个注释,这个例子显然假设10.5使用属性,但你可以使用访问器方法在10.4中做同样的事情.

猜你在找的C&C++相关文章