Search code examples
iosstructnsdictionaryproperty-list

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


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?


Solution

  • 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.