Reputation: 39081
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:
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
?
Upvotes: 0
Views: 88
Reputation: 5237
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.
Upvotes: 1
Reputation: 130193
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.
Upvotes: 1