Search code examples
iphoneiosnsstringnspredicate

ios using filteredArrayUsingPredicate NSPredicate with NSString not working


I'm using to get some of the content of nsmutable array and it work fine if I don't use nsstring to make the query:

NSLog(@"user information %@", [usersInfo filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"%K == 'Joe", @"id"]]);

But try to use a nsstring to query for the user it doesn't work:

NSString *user="Joe";

NSLog(@"user information %@", [usersInfo filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"%K == user", @"id"]]]);

any of you knows what I'm doing wrong? or what would be the best of doing it using NSString to query for users?


Solution

  • Use:

    NSLog(@"user information %@", [usersInfo filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:[NSString stringWithFormat:@"%K == '%@'",@"id",user]]]);
    

    When you use:

    NSLog(@"user information %@", [usersInfo filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"%K == user", @"id"]]]);"
    

    The user will be a part of the string, it won't replace with the content of the NSString object.