我的nsdictionary包含具有以下结构的元素
名称 - >值
电子邮件 - >键
我从用户那里得到(以上结构)的价值, 现在我想通过值(由用户输入)而不是按键搜索nsdictionary中的元素,无论它是否存在于nsdictionary中,并且还希望获得该元素的索引(如果存在)。
怎么做?
答案 0 :(得分:7)
最好这样做可能是
- (NSArray *)allKeysForObject:(id)anObject
这种NSDictionary
方法可以返回所有以anObject
为值的键。如果在整个字典中只有一个对象,它将在逻辑上返回一个只有一个键的数组。
答案 1 :(得分:4)
NSArray * users = ...; //your array of NSDictionary objects
NSPredicate *filter = [NSPredicate predicateWithFormat:@"email = test@gmail.com"];
NSArray *filteredContacts = [contacts filteredArrayUsingPredicate:filter];
对于多个电子邮件值,然后在谓词中使用OR:
filter = [NSPredicate predicateWithFormat:@"contact_type = 42 OR contact_type = 23"];
答案 2 :(得分:3)
字典数据结构没有“顺序”,因此您必须通过迭代集合并查找所需的值来搜索您的密钥。
示例:
NSString *targetKey = nil;
NSArray *allKeys = [collection allKeys];
for (int i = 0; i < [allKeys count]; ++i) {
NSString *key = [allKeys objectAtIndex:i];
NSString *obj = [collection objectForKey:key];
if ([obj isEqualToString:searchedString]) { // searchedString is what you're looking for
targetKey = key;
break;
}
}
// check if key was found (not nil) & proceed
// ...
答案 3 :(得分:0)
您可以在NSDictionary
中搜索输入的值,但无法获得值索引,因为NSDictionary没有键值对的顺序。
NSArray *array = [yourDictionaryObject allValues];
if ([array containsObject:@"userEnteredValue"]) {
<#statements#>
}
答案 4 :(得分:0)
您需要iterate through the Dictionary for the keys
具有您需要的价值:
试试这个:
NSArray *keys= [json allKeys];
for (NSString *keysV in keys){
NSLog(@"Keys are %@", keysV);
if([Your_Dict objectForKey: keysV] isEqual:@"string to Match"){
//Do your stuff here
}
}