代码之家  ›  专栏  ›  技术社区  ›  mmc

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

  •  7
  • mmc  · 技术社区  · 15 年前

    我把核心数据弄得乱七八糟,我确信我遗漏了一些明显的东西,因为我找不到一个与我试图做的事情完全相似的例子。

    假设我在玩DVD数据库。我有两个实体。一部电影(片名、年份、评级以及与演员的关系)和演员(姓名、性别、照片)。

    得到所有的电影都很容易。只是:

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

    获取所有标题中带有“Kill”的电影很容易,我只需添加一个NSPredicate:

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

    但核心数据似乎提取了托管对象的id字段。。。那么,如何查询作为对象的属性(或:查询关系)?

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

    2 回复  |  直到 15 年前
        1
  •  6
  •   Jason Coco    15 年前

    假设演员和电影实体之间存在一对多的反向关系,您只需以与获取任何特定实体相同的方式获取Chuck Norris的实体,然后访问附加到演员实体上关系的电影实体数组。

    // 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中使用访问器方法执行相同的操作。

        2
  •  5
  •   Igor    13 年前

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

    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;