按值搜索 nsdictionary 中的元素



我有 nsdictionary,其中包含具有以下结构的元素

名称 -->值

电子邮件-->键

我从用户那里获得(上述结构)的值,现在我想按值(由用户输入)而不是按键搜索 nsdictionary 中的元素,无论它是否存在于 nsdictionary 中,并且还想获取该元素的索引(如果存在)。

怎么做?

最好这样做

- (NSArray *)allKeysForObject:(id)anObject

这种NSDictionary方法会给你所有以anObject作为其值的键。如果整个字典中每个对象只有一次,它将在逻辑上返回一个只有一个键的数组。

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"];

字典数据结构没有"顺序",因此您必须通过迭代集合并查找所需的值来搜索键。

例:

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

您可以在 NSDictionary 中搜索输入的值,但无法获取值的索引,因为 NSDictionary 没有键值对的顺序。

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

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 
    }
}

最新更新