我怎样才能获得以某个字符串开头的NSMutableDictionary的键

时间:2010-05-25 07:43:25

标签: iphone objective-c

我有一个json响应即将到来,我需要获取其键是特定字符串的所有值...例如:www_name,www_age等在nsmutabledictionary中作为键进入现在我想要搜索所有这些值具有“ www_“作为字符串的一部分。

2 个答案:

答案 0 :(得分:21)

循环字典并过滤。

NSMutableArray* result = [NSMutableArray array];
for (NSString* key in dictionary) {
  if ([key hasPrefix:@"www_"]) {
    [result addObject:[dictionary objectForKey:key]];
    // write to a dictionary instead of an array
    // if you want to keep the keys too.
  }
}
return result;

答案 1 :(得分:13)

您可以让字典过滤结果并使用NSPredicate返回数组,而不是自己迭代集合。

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF beginswith www_"];
NSArray *filtered = [[dictionary allKeys] filteredArrayUsingPredicate:predicate];

只是一个想法。