user1107173
user1107173

Reputation: 10784

Core Data: Using Predicates with to-many Relationship

To-Many relationship in Entity "Meetings" <--->> "Users"

I made a NSManagedSubclass for "Meetings" and it has a property:

@property (nonatomic, retain) NSSet *users;

Objects in *users save fine and I can see them. But when I try to fetch, nothing happens. I have the breakpoint setup inside the Block and it seems like the fetch Block never reaches the breakpoint. No errors. Applications is still running.

I have the following code:

        NSString *userName = @"iphone";
        NSLog(@"Username %@", userName);

        NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:@"Meeting"];
        NSPredicate *predicate = [NSPredicate predicateWithFormat:@"users.username == %@", userName];
        NSLog(@"Predicate %@", predicate);
        [request setPredicate:predicate];

        [self.managedObjectContext executeFetchRequest:request onSuccess:^(NSArray *results)
         { // I have setup the breakpoint here 
             NSLog(@"results.count %i", results.count);

             if(results.count > 0)
             {
                 NSLog(@"object found");
             }
         }onFailure:^(NSError *error) {
                  NSLog(@"There was an error! %@", error);
         }];

Log:

2013-10-12 20:10:19.200 App[3128:c07] Username iphone
2013-10-12 20:10:19.200 App[3128:c07] Predicate users.username == "iphone"

I can fetch for other attributes in Meetings just fine. i.e. If I replace the predicate line with :

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"meetings_id == %@", meetings_id];

And the breakpoint will stop the code, the will show "object found".

Again, I can see the "iphone" user inside the users relationship. What am I doing wrong?

Upvotes: 0

Views: 1309

Answers (1)

punycode
punycode

Reputation: 556

For to-many relationships you have to use a predicate modifier, that states what is the intended behaviour. Since you are searching for Meetings, CoreData cannot figure out from your predicate users.username == %@, if you want Meetings where ALL users have the specified username or only those where ANY single user meets the requirements (see here for in-depth documentation).

Try this for a change, since I think it is what you would want:

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"ANY users.username == %@", userName]

Upvotes: 3

Related Questions