问题
Using StackMob as backend. I have an Event
entity which has a relationship called user users
(type NSSet
). Right now I want to get all the events that some user's username
is @"someuser"
. My code like this:
[self.client getLoggedInUserOnSuccess:^(NSDictionary *result) {
NSString *currentlyLoggedInUser = [result valueForKey:@"username"];
NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSEntityDescription *eventEntity = [NSEntityDescription entityForName:@"Event" inManagedObjectContext:self.managedOjbectContext];
[request setEntity:eventEntity];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"ANY users.username = %@", currentlyLoggedInUser];
NSLog(@"predicate: %@", predicate);
[request setPredicate:predicate];
NSLog(@"request: %@", request);
events = [NSArray new];
events = [self.managedOjbectContext executeFetchRequest:request error:nil];
/* this is working...
for (Event *e in events) {
NSLog(@"%@",[e.users filteredSetUsingPredicate:[NSPredicate predicateWithFormat:@"username == %@", currentlyLoggedInUser]]);
}
*/
NSLog(@"events: %@", events);
} onFailure:^(NSError *error) {
}];
回答1:
If I understand your question correctly, you have to use the following predicate:
NSString *userName = @"some user";
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"ANY users.username = %@", userName];
It finds all events that have any user with the given user name.
回答2:
Assuming you have a User entity and an Event entity, you have to pass a User to the predicate, not just the name.
User *loggedInUser = // anything, e.g.
User *loggedInUser = [[allUsers filteredSetUsingPredicate:
[NSPredicate predicateWithFormat:
@"username == %@", currentlyLoggedInUser] anyObject];
fetchRequest.predicate = [NSPredicate predicateWithFormat:
@"%@ in users", loggedInUser]
来源:https://stackoverflow.com/questions/15026586/how-can-i-use-predicatewithformat-for-query-a-nsstring-is-contained-in-an-nsset