1

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);
        }
}
Ric Levy
  • 966
  • 1
  • 15
  • 33

3 Answers3

3

You're comparing the pointers of the return values of eachItem.priority and [NSNumber numberWithInt:1]. You should use NSNumber's equality method.

Cajunluke
  • 3,103
  • 28
  • 28
2

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,

Ravin
  • 8,544
  • 3
  • 20
  • 19
  • But I have read that NSNumber has - (int)intValue method? Is there something wrong in documentation?please mention. – Ravin Apr 14 '11 at 16:36
1

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.

walkytalky
  • 9,453
  • 2
  • 36
  • 44