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 o开发者_如何学Gother 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?
Actually the correct way to format a predicate to exclude quotes is the to use %K
versus %@
. See Predicate Format String Syntax.
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:@""];
精彩评论