简体   繁体   English

nsdictionary中按值搜索的元素

[英]Search element in nsdictionary by value

I have nsdictionary which contains elements with following structure 我有nsdictionary,其中包含具有以下结构的元素

name --> value 名称->值

email--> key 电子邮件->密钥

I get value(of above structure) from user, now I want to search element in nsdictionary by value(entered by user) not by key, whether it is present in nsdictionary or not and also want to get index of that element if present. 我从用户那里得到了(具有上述结构的值),现在我想按值(由用户输入)而不是按键在nsdictionary中搜索元素,无论它是否存在于nsdictionary中,并且还希望获取该元素的索引(如果存在)。

How to do this? 这个怎么做?

The best to do so would propably be 最好的做法是

- (NSArray *)allKeysForObject:(id)anObject

This method of NSDictionary gives you back all the keys having anObject as their value. NSDictionary此方法为您提供以anObject作为其值的所有键。 If you only have each object once in the whole dictionary it will logically return an array with only one key in it. 如果整个字典中每个对象只有一次,它将在逻辑上返回仅包含一个键的数组。

NSArray * users = ...; //your array of NSDictionary objects
NSPredicate *filter = [NSPredicate predicateWithFormat:@"email = test@gmail.com"];
NSArray *filteredContacts = [contacts filteredArrayUsingPredicate:filter];

for more than one value of email, then use an OR in the predicate: 要获取多个电子邮件值,请在谓词中使用OR:

filter = [NSPredicate predicateWithFormat:@"contact_type = 42 OR contact_type = 23"];

The dictionary data structure has no 'order', so you'd have to search for your key by iterating the collection and looking for the desired value. 字典数据结构没有“顺序”,因此您必须通过迭代集合并寻找所需的值来搜索关键字。

Example: 例:

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
// ...

You can search the entered value in NSDictionary , but you can't get an index of value , as NSDictionary has no order of key value pair. 您可以在NSDictionary搜索输入的值,但由于NSDictionary没有键值对的顺序,因此无法获得值的索引。

    NSArray *array = [yourDictionaryObject allValues];
    if ([array containsObject:@"userEnteredValue"]) {
       <#statements#>
    }

You need to iterate through the Dictionary for the keys has the Value of your need: Try this: 您需要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 
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM