How to get data from a NSDictonary in a NSDictonary in a property list?

88 views Asked by At

I have a plist with an NSDictonary in an NSDictonary and I wonder if there is an easy way to get data from the sub NSDictonary.

Here is a picture of how my plist looks like: my plist

I want to get the data from the NSDictonary's Pistol, Magnum and ShotGun.

I thought there would be a method in NSDictonary like this dictonaryForKey but there isnt one and I cant seem to find something similar.

NSString *plistURL = [[NSBundle mainBundle] pathForResource:@"Guns" ofType:@"plist"];
NSDictionary *guns = [[NSDictionary alloc] initWithContentsOfFile:plistURL];
NSArray *array = [dict allValues];
NSDictionary *pistol = [[NSDictionary alloc] initWithDictionary:array[0]];
NSNumber *number = [newDict valueForKey:@"Damage"];

Or is there a way to set values in a struct?

2

There are 2 answers

1
Mick MacCallum On BEST ANSWER

I think you're over complicating things for yourself. Try the following code, it creates your initial dictionary, then directly accesses the sub dictionary by its key value.

NSString *plistURL = [[NSBundle mainBundle] pathForResource:@"Guns" ofType:@"plist"];
NSDictionary *guns = [[NSDictionary alloc] initWithContentsOfFile:plistURL];

NSDictionary *pistol = guns[@"Pistol"];
NSNumber *number = pistol[@"Damage"];

Note: The last two lines utilize modern Objective C syntax.

2
Pedro Mancheno On

Use Key Value Coding:

NSString *plistURL = [[NSBundle mainBundle] pathForResource:@"Guns" ofType:@"plist"];
NSDictionary *guns = [[NSDictionary alloc] initWithContentsOfFile:plistURL];
NSDictionary *pistol = [guns valueForKeyPath:@"Pistol"];

Or if you want to get the damage directly:

NSNumber *damage = [guns valueForKeyPath:@"Pistol.Damage"];

From the documentation:

- (id)valueForKeyPath:(NSString *)keyPath

Returns the value for the derived property identified by a given key path. The default implementation gets the destination object for each relationship using valueForKey: and returns the result of a valueForKey: message to the final object.