0

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?

4

2 回答 2

1

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.

于 2013-08-30T13:48:14.607 回答
1

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.

于 2013-08-30T13:49:22.817 回答