2011-04-14 118 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是其中之一。然而,依靠這種方式將是非常糟糕的形式,即使它恰好在這種情況下工作。

相關問題