2011-04-14 69 views
1

我正在通过我的表中的ChecklistItem实体进行枚举,以查看哪些人具有priority(NSNumber属性)为1. checklistItemsChecklist处于多对多关系。为什么这个简单的'if'语句不工作(在快速枚举中)?

在这个简单的代码中,第一个NSLog工作正常,并报告我的几个ChecklistItems的优先级为1.但是第二个NSLog永远不会被调用。为什么是这样?我假设我正在构思错误的“如果”陈述,但我不知道如何。

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); 
     } 
} 

回答

2

您无法像上面那样比较对象。使用下面的代码。

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); 
     } 
} 

感谢,

+0

这是行不通的,eachItem.priority是一个NSNumber – MarkPowell 2011-04-14 16:34:15

+0

但我读过NSNumber有 - (int)intValue方法吗?文档中有什么问题吗?请提一下。 – Ravin 2011-04-14 16:36:49

+0

我的错误,应该仔细阅读。错过了你的“intValue”。 – MarkPowell 2011-04-14 16:41:18

3

你比较eachItem.priority[NSNumber numberWithInt:1]返回值的指针。你应该使用NSNumber的平等方法。

1

那么,你应该检查值相等这样的事情:

if ([eachItem.priority intValue] == 1) { ... } 

不过,我有点惊讶它不意外的工作,因为它是,因为我认为NSNumber汇集几个基础实例,我希望1是其中之一。然而,依靠这种方式将是非常糟糕的形式,即使它恰好在这种情况下工作。

相关问题