How can I use predicateWithFormat for query a NSString is contained in an NSSet

拥有回忆 提交于 2019-12-11 14:11:36

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!