【问题标题】:How to do Core Data queries through a relationship?如何通过关系进行 Core Data 查询?
【发布时间】:2010-10-25 01:20:34
【问题描述】:

我在搞乱 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']),“给我所有由 [Object id 1 主演的电影”的谓词格式是什么- '查克诺里斯']"?

【问题讨论】:

    标签: objective-c cocoa macos core-data


    【解决方案1】:

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

    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;
    

    【讨论】:

      【解决方案2】:

      假设 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 中使用访问器方法做同样的事情。

      【讨论】:

      • 我会,假设关系是双向建立的,Core Data 会为您完成,我需要的代码是:NSSet *moviesWithChuck = chuck.movies;。基本上,Core Data 自己检索链接的实体。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-08
      • 1970-01-01
      • 2014-12-28
      • 1970-01-01
      相关资源
      最近更新 更多