1

我正在枚举ChecklistItem表中的实体,以查看哪些实体的priority(NSNumber 属性)为 1。checklistItemsChecklist.

在这个简单的代码中,第一个 NSLog 工作正常,并报告我的几个 ChecklistItems 的优先级为 1。但第二个 NSLog 永远不会被调用。为什么是这样?我认为我错误地构建了“if”语句,但我不知道如何。

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

3 回答 3

3

您正在比较 和 的返回值的eachItem.priority指针[NSNumber numberWithInt:1]。您应该使用NSNumber' 相等方法。

于 2011-04-14T16:32:31.667 回答
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);
        }
}

谢谢,

于 2011-04-14T16:32:25.933 回答
1

好吧,你应该像这样检查值相等:

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

但是,我有点惊讶它不会意外地按原样工作,因为我认为NSNumber汇集了一些基本实例,我希望 1 是其中之一。但是,即使它碰巧在这种情况下起作用,依赖它也是非常糟糕的形式。

于 2011-04-14T16:33:45.683 回答