How to do Core Data queries through a relationship?

前端 未结 2 1667
灰色年华
灰色年华 2021-01-31 12:53

I\'m messing around with Core Data, and I am sure I am missing something obvious, because I cannot find an example that at all resembles what I am trying to do.

Let\'s s

2条回答
  •  死守一世寂寞
    2021-01-31 13:06

    Assuming that there is a one-to-many inverse relationship between the Actor and the Movie entities, you can just get the entity for Chuck Norris the same way you would get any specific entity, and then access the array of Movie entities attached to the relationship on the Actor entity.

    // 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;
    

    As a note, this example obviously assumes 10.5 using properties, but you can do the same thing in 10.4 using accessor methods.

提交回复
热议问题