简体   繁体   中英

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?

When you write

NSString *user = @"Joe";
... [NSPredicate predicateWithFormat:@"%K == user", @"id"]

you seem to expect that "user" in the predicate is replaced by the contents ("Joe") of the NSString variable, but this is not correct.

You have to give the string as another argument to the predicate and add the %@ format that will be expanded by the string.

NSString *user = @"Joe";
... [NSPredicate predicateWithFormat:@"%K == %@", @"id", user]

Here %K (which is var arg substitution for a key path ) will be substituted by the key "id" , and %@ (which is var arg substitution for an object value) will be substituted by the contents of the user variable.

Using %K expansion instead of

[NSPredicate predicateWithFormat:@"id == %@", user]

has the advantage that it works correctly even if the key is a reserved word in the predicate format string syntax.

I am unable to gues why you are using "%K == 'Joe"

Anyways, You can use predicate as:

[NSPredicate predicateWithFormat:@"object.property LIKE[c] %@", stringValue];

Or,

[NSPredicate predicateWithFormat:@"object.property==[c] %@", stringValue];

try this:

NSString *user="Joe";

NSLog(@"user information %@", [usersInfo filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"SELF contains [cd] %@", user]]]);

Make your predicate format string before don't try to add property name inside predicate format :

NSString *predicateFormat = [NSString stringWithFormat:@"%@ == %%@",@"id"];
NSPredicate *predicate = [NSPredicate predicateWithFormat: predicateFormat, @"Joe"];
NSArray *filteredArray = [mutableArray filteredArrayUsingPredicate:predicate];

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM