簡體   English   中英

使用NSPredicate過濾NSDray對象的NSArray

[英]Filtering NSArray of NSDictionary objects using NSPredicate

我有一個NSDray的NSDictionary對象。 我想使用NSPredicate根據字典的鍵過濾數組。 我一直在做這樣的事情:

NSString *predicateString = [NSString stringWithFormat:@"%@ == '%@'", key, value];
NSPredicate *predicate = [NSPredicate predicateWithFormat:predicateString];
NSArray *filteredResults = [allResultsArray filteredArrayUsingPredicate:predicate];

如果傳入的密鑰是單字,則可以正常工作:顏色,名稱,年齡。 但如果密鑰是多字的,它就不起作用,例如:人物年齡,人名。

基本上,任何包含空格的鍵,它都不起作用。 我已經嘗試在字符串中的鍵周圍放置單引號,就像它們在值側完成但是也不起作用。 也試過雙引號,但無濟於事。

請告知此事。 提前致謝。

對我來說,凱文的答案沒有用。 我用了:

NSPredicate *predicateString = [NSPredicate predicateWithFormat:@"%K contains[cd] %@", keySelected, text];//keySelected is NSString itself
        NSLog(@"predicate %@",predicateString);
        filteredArray = [NSMutableArray arrayWithArray:[YourArrayNeedToFilter filteredArrayUsingPredicate:predicateString]];

使用動態密鑰時,應使用%K標記而不是%@ 您也不希望值標記周圍的引號。 它們將使您的謂詞測試與文字字符串@"%@"相等性而不是value

NSString *predicateString = [NSString stringWithFormat:@"%K == %@", key, value];

這在Predicate Format String Syntax指南中有記錄


編輯:正如Anum Amin指出的那樣, +[NSString stringWithFormat:]不處理謂詞格式。 你想要[NSPredicate predicateWithFormat:@"%K == %@", key, value]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM