GangstaGraham
GangstaGraham

Reputation: 9375

Find User's Groups Using NSPredicate

My fetch request is getting all the group objects rather than the ones I want.

I want it to fetch only the groups that the current user is a part of, but my predicate does not seem to be working. Any thoughts to what's wrong?

    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    [fetchRequest setEntity:[NSEntityDescription entityForName:@"AGroup" inManagedObjectContext:_managedObjectContext]];
    AUser *u = [AUser currentUser];  //gets app's current user
    [fetchRequest setPredicate:[NSPredicate predicateWithFormat:@"ANY users = %@", u]];

I have also tried the following, which did not work:

[NSPredicate predicateWithFormat:@"(users CONTAINS %@)", u];
[NSPredicate predicateWithFormat:@"SUBQUERY(users, $user, $user = %@).@count = [users count]", u];

Class Structure

AGroup
- users (Type: AUser *)

AUser
- name (Type: NSString *)

Upvotes: 1

Views: 82

Answers (1)

Martin R
Martin R

Reputation: 539975

I cannot see why

[NSPredicate predicateWithFormat:@"ANY users = %@", u]

does not work for you, but the easier solution is just to use the inverse relationship

AUser *u = [AUser currentUser];
NSSet *theGroups = u.groups;

or, if you need it as an array:

NSArray *theGroups = [u.groups allObjects];

Upvotes: 1

Related Questions