Why won't this simple 'if' statement work (inside fast enumeration)?
I am enumerating through the ChecklistItem
entities in my table to see which ones have a priority
(NSNumber attribute) of 1. checklistItems
are in a to-many relationship with Checklist
.
In this simple code, the first NSLog works fine, and reports that several of my ChecklistItems have a priority of 1. But the second NSLog never gets called. Why is this? I assume I'm framing the "if" statement wrong, but I don't know how.
for (ChecklistItem *eachItem in checklist.checklistItems){
NSLog(@"Going through loop. Item %@ has priority %@.", eachItem.name, eachItem.priority);
if (eachItem.priority == [NSNumber numberWithInt:1]) {
NSLog(@"Item %@开发者_开发问答 has priority 1", eachItem.name);
}
}
You're comparing the pointers of the return values of eachItem.priority
and [NSNumber numberWithInt:1]
. You should use NSNumber
's equality method.
You can not compare objects as you did above. Use the following code.
for (ChecklistItem *eachItem in checklist.checklistItems){
NSLog(@"Going through loop. Item %@ has priority %@.", eachItem.name, eachItem.priority);
if ([eachItem.priority intValue]== 1) {
NSLog(@"Item %@ has priority 1", eachItem.name);
}
}
Thanks,
Well, you should be checking for value equality something like this:
if ( [eachItem.priority intValue] == 1 ) { ... }
However, I'm kind of surprised it doesn't accidentally work as it is, because I thought NSNumber
pooled a few base instances and I'd expect 1 to be one of them. Relying on that would be very bad form, though, even if it happened to work in this case.
精彩评论