2013-01-06 81 views
3

的陣列我有NSNumber秒的陣列,例如:10015,12313,10016NSPredicate與NSNumbers

我要檢查,如果數組包含我在搜索欄輸入了整數。

我的代碼:

NSPredicate *resultPredicate = [NSPredicate 
    predicateWithFormat:@"SELF CONTAINS[c] %d", [searchText intValue]]; 


self.searchResults = [newArr filteredArrayUsingPredicate:resultPredicate]; 

回答

9

如果你需要的是數組是否包含它的布爾值,那麼你想要的。

self.searchResults = [newArr containsObject:@([searchText intValue])]; 

如果你真的想要的NSNumber S IN的結果(在這種情況下,1)的一個子集,則包含將無法工作。必須檢查每個NSNumber這樣的價值的平等......

NSPredicate *resultPredicate = [NSPredicate 
    predicateWithFormat:@"SELF == %d", [searchText intValue]]; 
0

如果你只是想知道,如果數量是數組中,有沒有必要使用謂詞:

BOOL occurs = [newArr containsObject:[NSNumber numberWithInt:[searchText intValue]]]; 

應該這樣做。

+2

這將無法正常工作,是因爲你需要傳遞一個對象,而不是一個'int'。試試這個'[newArr containsObject:@([searchText intValue])];'。這會將'int'包裝在'NSNumber'中。 – rmaddy

+0

@rmaddy謝謝!在發佈之前,應該真正嘗試編譯我的示例代碼。 – Chris