Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSDictionary inside NSDictionary

Ok I have a .plist file,

In which I have an NSDictionary *StoredAddresses,

Inside StoredAddresses, is another handful of NSDictionary

I know I can use,

if ([dictionaryOfAddresses objectForKey:@"StoredAddresses"])

To access the top level NSDictionaries, but how can I search for keys inside the stored addresses?

like image 755
Taskinul Haque Avatar asked Sep 19 '12 08:09

Taskinul Haque


2 Answers

Well, if I read this correctly, you have dictionaries within dictionaries. This works just like any other object:

NSDictionary* Address=[dictionaryOfAddresses objectForKey:@"Home Address"];
NSString* Street=[Address objectForKey:@"Street"];

You could combine the calls if you want to:

NSString* Street=[[dictionaryOfAddresses objectForKey:@"Home Address"] objectForKey:@"Street"];
like image 175
Christian Stieber Avatar answered Sep 24 '22 12:09

Christian Stieber


You can use the NSKeyValueCoding method valueForKeyPath: to access properties of nested objects. For example, given the following dictionaries...

NSDictionary *homeAddressDict = @{ @"street" : @"2 Elm St.", @"city" : @"Reston" };
NSDictionary *addressesDict = @{ @"home" : homeAddressDict };

...you can access values of the nested home dictionary as follows:

NSString *street = [addressesDict valueForKeyPath:@"home.street"];
NSString *city = [addressesDict valueForKeyPath:@"home.city"];

This works the same for more deeply nested paths, for example:

NSDictionary *contactDict = @{ @"name" : @"Jim Ray", @"addresses" : addressesDict };

NSString *street2 = [contactDict valueForKeyPath:@"addresses.home.street"];
NSString *city2 = [contactDict valueForKeyPath:@"addresses.home.city"];

Note that this will work regardless of whether the objects are instances of NSDictionary or any custom class that descends from NSObject, provided that the custom class has properties or instance variables whose names match the keys.

So for example, instead of using an NSDictionary for home address, you could substitute an instance of a custom Address class that had declared properties, getter methods, or instance variables named street and city (or instance variables named _street and _city), and still access it the same way.

And if the object containing the target property is mutable (for example an instance of NSMutableDictionary), you can even modify the value using the same mechanism, for example:

[contactDict setValue:@"Herndon" forKeyPath:@"addresses.home.city"];
like image 35
jlehr Avatar answered Sep 21 '22 12:09

jlehr