Core data join table, has many through, fetched properties predicate

后端 未结 2 1037
有刺的猬
有刺的猬 2021-02-04 16:06

\"Xcode How do you write a Fetched Property for the Place Entity that will present an Array of Users?

2条回答
  •  天涯浪人
    2021-02-04 16:35

    For a fetched property users of Place that retrieves all users whose check-in is related to the given place, set

    • the destination of the fetched property to "User"
    • and the predicate to "ANY checkins.event == $FETCH_SOURCE"

    enter image description here

    Now you can get the array of users for a place:

    Place *place = ...;
    NSArray *users = [place valueForKey:@"users"];
    

    This fetched property corresponds to the following fetch request:

    Place *place = ...;
    NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"User"];
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"ANY checkins.event == %@", place];
    [request setPredicate:predicate];
    NSArray *users = [context executeFetchRequest:request error:&error];
    

    If you declare the fetched property users as a dynamic property:

    @interface Place (FetchedProperties)
    @property(nonatomic, retain) NSArray *users;
    @end
    
    @implementation Place (FetchedProperties)
    @dynamic users;
    @end
    

    then you can retrieve the value using property syntax:

    NSArray *users = place.users;
    // instead of: NSArray *users = [place valueForKey:@"users"];
    

    But note that you can get the same result (as a set) directly, without using a fetched property:

    Place *place = ...;
    NSSet *users = [place.checkins valueForKey:@"user"];
    

提交回复
热议问题