thekevinscott
thekevinscott

Reputation: 5413

NSPredicate, with quotes / without quotes

In my iPhone app, I'm reading a csv file. The relevant line is this:

NSString *countrycode = [[[NSString alloc] initWithFormat:@"%@", [arr objectAtIndex:2]] 
                                 stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];

This returns "CN" (which stands for China).

When I do this:

NSLog(@"Manual: %@, country code: %@",@"CN",countryCode);

I get:

Manual: CN, country code: "CN"

One has quotes and the other does not. I don't know why this is.

The reason this is tripping me up is the following:

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

This works fine, and returns China from Core Data.

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

This fails to return anything. I am assuming this is because it has quotes around it, or something, although perhaps I am incorrect.

What am I doing wrong here?

Upvotes: 3

Views: 1527

Answers (2)

Joel
Joel

Reputation: 16124

Actually the correct way to format a predicate to exclude quotes is the to use %K versus %@. See Predicate Format String Syntax.

Upvotes: 20

George Johnston
George Johnston

Reputation: 32258

Your countryCode variable must have quotes inside of it when it's read back. The first time you assign the literal @"CN" the quotes are removed as they specify that your variable is an NSString. They aren't really inside of the literal string. If you wanted strings inside of the first CN, you'd need to explicitly specify the quotation marks, e.g. @"""CN"""

However, if you want to get rid of any quotations in the second string, you could always do this to the string prior to putting it into your predicate:

[countryCode stringByReplacingOccurrencesOfString:@"""" withString:@""];

Upvotes: -1

Related Questions