Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

ios

core-data

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

like image 847
fzf Avatar asked Jan 19 '13 06:01

fzf


2 Answers

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"];
like image 78
Martin R Avatar answered Nov 19 '22 21:11

Martin R


I hope I did understand you correctly. You want a list of users that have checked in at a certain place?

Then you do it the other way around. You fetch all Users that have at least one Checkin with a certain Place.

In Core-Data terms you'll need a subquery for this.

NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"User"];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SUBQUERY(checkins, $CHECKIN, $CHECKIN.event == %@).@count > 0", place];
request.predicate = predicate;
/* and so on */

There is not much documentation about SUBQUERY. A little bit is written in the discussion of expressionForSubquery:usingIteratorVariable:predicate:.

And the fetched property would be in the Place entity with a destination entity User and the predicate SUBQUERY(checkins, $CHECKIN, $CHECKIN.event == $FETCH_SOURCE).@count > 0

like image 23
Matthias Bauch Avatar answered Nov 19 '22 21:11

Matthias Bauch