Iphone 如何获取以特定字符串开头的NSMutableDictionary键
我有一个json响应即将到来,我需要得到所有的值,它们的键是一个特定的字符串。。。例如:www\u name、www\u age等作为键出现在nsmutabledictionary中,现在我想搜索所有那些以“www\u”作为字符串一部分的值。在字典和过滤器上循环Iphone 如何获取以特定字符串开头的NSMutableDictionary键,iphone,objective-c,Iphone,Objective C,我有一个json响应即将到来,我需要得到所有的值,它们的键是一个特定的字符串。。。例如:www\u name、www\u age等作为键出现在nsmutabledictionary中,现在我想搜索所有那些以“www\u”作为字符串一部分的值。在字典和过滤器上循环 NSMutableArray* result = [NSMutableArray array]; for (NSString* key in dictionary) { if ([key hasPrefix:@"www_"]) {
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;
您也可以要求字典为您过滤结果,并使用NSPredicate返回数组,而不是自己迭代集合
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF beginswith www_"];
NSArray *filtered = [[dictionary allKeys] filteredArrayUsingPredicate:predicate];
只是一个想法。如果你想得到一个真正的过滤字典,你可以做
[字典字典带值:过滤]
。甚至更漂亮。感谢您提供的提示。“valueForUndefinedKey:]:该类与键的键值编码不兼容”?谓词应为:NSPredicate*谓词=[NSPredicate predicateWithFormat:@“带“www”的self begins]代码>或如果您希望区分大小写NSPredicate*谓词=[NSPredicate predicate-withformat:@“self BEGINSWITH[cd]”www_u')代码>hasPrefix:
和hasSuffix:
非常有用。谢谢你的提示。