简体   繁体   中英

Get a value from nsdictionary

I want to give a key value from my NSDictionary and get the value associated to it. I have this:

NSArray *plistContent = [NSArray arrayWithContentsOfURL:file];
NSLog(@"array::%@", plistContent);

dict = [plistContent objectAtIndex:indexPath.row];

cell.textLabel.text = [dict objectForKey:@"code"];

with plistContent :

(
        {
        code = world;
        key = hello;
    },
        {
        code = 456;
        key = 123;
    },
        {
        code = 1;
        key = yes;
    }
)

So how do I get "hello" by giving the dictionary "world"?

If I understand your question correctly, you want to locate the dictionary where "code" = "world" in order to get the value for "key".

If you want to keep the data structure as it is, then you will have to perform a sequential search, and one way to do that is simply:

NSString *keyValue = nil;
NSString *searchCode = @"world";
for (NSDictionary *dict in plistContents) {
    if ([[dict objectForKey:@"code"] isEqualToString:searchCode]) {
        keyValue = [dict objectForKey:@"key"]);    // found it!
        break;
    }
}

However if you do alot of this searching then you are better off re-organizing the data structure so that it's a dictionary of dictionaries, keyed on the "code" value, converting it like this:

NSMutableDictionary *dictOfDicts = [[NSMutableDictionary alloc] init];
for (NSDictionary *dict in plistContents) {
    [dictOfDicts setObject:dict
                    forKey:[dict objectForKey:@"code"]];
}

(note that code will break if one of the dictionaries doesn't contain the "code" entry).

And then look-up is as simple as:

NSDictionary *dict = [dictOfDicts objectForKey:@"world"]);

This will be "dead quick".

- (NSString*) findValueByCode:(NSString*) code inArray:(NSArray*) arr
{   
    for(NSDictonary* dict in arr)
    {
        if([[dict valueForKey:@"code"] isEqualToString:code])
        {
             return [dict valueForKey:@"key"]
        }
    }

    return nil;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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