2015-06-08 92 views
0

我有一個非常簡單的NSPredicate,它應該過濾我的自定義對象數組。爲什麼這個簡單的NSPredicate過濾我的數組

NSLog(@"%@", self.displayedSources); 
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name CONTAINS[cd] %@", searchText]; 
[self.displayedSources filterUsingPredicate:predicate]; 
NSLog(@"%@", self.displayedSources); 

然而,這給我留下了0的結果(即使searchText)。

我知道數組中填充自定義類型,其中報頭看起來像這樣

@interface NewsSourceObject : NSObject <NSCoding> 
@property (nonatomic, copy, readonly) NSString *objectId; 
@property (nonatomic, copy, readonly) NSString *name; 
... 
@end 

我知道正在執行的代碼,因爲我已經添加打印語句記錄的長度的26個目的數組應用謂詞(26 - 0)之前和之後的數組。

我一直用這個拉我的頭髮半天以上,因爲我不知道什麼是錯的。

EDIT 1: 我嘗試之前以及將所述謂詞後記錄所述數組的內容使用的對象此description方法(參見頂部代碼塊):

- (NSString *)description { 
    return [NSString stringWithFormat:@"%@", self.name]; 
} 

而這正是我得到:

2015-06-08 02:57:28.521 Newsloop[8554:1578121] (
    "ABC News", 
    "BBC News", 
    "Bleacher Report", 
    "Business Insider", 
    "BuzzFeed News", 
    CNN, 
    "Daily Mail Online", 
    ... 
) 
2015-06-08 02:57:28.522 Newsloop[8554:1578121] (
) 
+0

是名稱字段實際上填入你的對象? –

+0

是的,我嘗試打印數組和所有名稱字段包含文本 – Aleksander

+0

無關,但爲什麼屬性聲明「複製」不「保留」? –

回答

1

胡亂猜測,但我的理論是,你不運行過濾後「重啓」 self.displayedSources。由於您在過濾數組時,一個錯誤的按鍵將永遠清除該數組。

您可能會運行那部分代碼,而searchText仍包含空字符串。這基本上從數組中刪除所有的對象。每個連續的鍵擊都在空陣列上運行一個過濾器。

存放在不同的變量,而不是過濾數組:

NSLog(@"%@", self.displayedSources); 
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name CONTAINS[cd] %@", searchText]; 

NSArray *filtered = [self.displayedSources filteredArrayUsingPredicate:predicate]; 

NSLog(@"%@", filtered); 
+0

你確實是對的,我只打你幾秒鐘哈哈(檢查原來的評論線程)。非常感謝你的幫助:) – Aleksander

相關問題