NSPredicate用于NSDictionary键的数组

时间:2013-10-22 12:14:33

标签: ios nsmutablearray nsdictionary nspredicate

我有

NSDictionary *myDictionary = @{ @"1":@"Egg Benedict",
                                @"2":@"Mushroom Risotto",
                                @"3":@"Full Breakfast",
                                @"4":@"Hamburger",
                                @"5":@"Ham and Egg Sandwich",
                                @"6":@"Cream Brelee"};
NSMutableArray *myKeys = [NSMutableArray arrayWithArray:[myDictionary allKeys]];

我想用谓词过滤myDictionary。我应该如何构建它? 作为一种算法,我想它应该是这样的:

[filteredKeys removeAllObjects];
for (NSString *a in myKeys) {
    if ([[myDictionary objectForKey:a] rangeOfString:searchText].location != NSNotFound) {
        [filteredKeys addObject:a];
    }
}

如何使用谓词字符串实现这一目标?

1 个答案:

答案 0 :(得分:0)

您有myObjects作为可变数组键,因此您可以过滤该数组。键只是字符串。这个谓词应该是:

@"SELF contains[c] %@", searchText

一旦过滤了数组,您就可以使用以下内容获取更新的字典:

NSDictionary *filtered = [myDictionary dictionaryWithValuesForKeys:myObjects];