Why can I not identify simple string key values in a database (core data)
I am a newbie so I apologise if I am missing something obvious.
I am trying to write an app in Xcode 4 to produce stats for my local sports team.
This is the relevant detail of the problem area of my programme:
NSError *error;
NSArray *games = [context executeFetchRequest:fetchRequest error:&error];
if (games == nil) {
NSLog(@"There was an error!");
}
int noOfBatOuts = games.count;
int noOfNotOuts=0;
for (NSManagedObject *oneMatch in games) {
if ([oneMatch valueForKey:@"batOut"]==@"NO") {
noOfBatOuts = noOfBatOuts - 1;
noOfNotOuts = noOfNotOuts + 1;
NSLog(@"Not Out!");
}
NSLog(@"How out %@",[oneMatch valueForKey:@"batOut"]);
}
notOuts.text=[NSString stringWithFormat:@"%d",(noOfNotOuts)];
NSLog(@"No of Not Outs is %@",notOuts.text);
When I run with data that has a not out string - NO, - the NSLog(@"Not Out!") is never called and the final NSLog(@"No of Not Outs...) reports zero. However I know that the data is there and it开发者_C百科 is identified in the middle NSLog(@"How Out....).
I am starting to tear my hair out in frustration and not having the knowledge yet to know the answer. Can anybody help please?
I would assume that batOut
is a Boolean rather than string type, in which case you should be checking for truth rather than string equality.
If batOut
really is a string, then you still can't compare strings this way. You need to use isEqual:
or isEqualToString:
. For example:
if ([[oneMatch valueForKey:@"batOut"] isEqual:@"NO"]) {
Normally you'd use isEqualToString:
for string comparisons, but -valueForKey:
is an id
so isEqual:
is safer.
The ==
operator checks that two pointers have the same value. Two strings can have the same contents but not be stored in the same memory.
You can't compare strings with ==. Use NSString's isEqualToString:
精彩评论