Dmitriy Babinskiy
Dmitriy Babinskiy

Reputation: 85

Dictionary from plist

i have 3 plist files with named level0, level1, level2, all of this plist have the same structure, it consist of number variable and array. I init my app with data from this plist.

+(instancetype)levelWithNum:(int)levelNum; {
    NSString* fileName = [NSString stringWithFormat:@"level%i.plist", levelNum];
    NSString* levelPath = [[[NSBundle mainBundle]resourcePath]stringByAppendingPathComponent:fileName];
    NSDictionary *levelDic = [NSDictionary dictionaryWithContentsOfFile:levelPath];
    NSAssert(levelDic, @"level no loaded");
    Level *l = [[Level alloc]init];
    l.coinsPerLvl = [levelDic[@"coinsPerLvl"] integerValue];
    l.words = levelDic[@"words"];
    return l;
}

Now i decide to use only one plist and add in it 3 dictionary. How can i read only one dictionary from plist like in example above where i use plist files.

Tanks for any help!

enter image description here

Upvotes: 0

Views: 181

Answers (2)

asanga
asanga

Reputation: 1

make your plist root as an array (like below). that way you can get levels info easily.

sample code

+(void)levelWithNum:(int)levelNum {

NSString* fileName = @"level.plist";
NSString* levelPath = [[[NSBundle mainBundle]resourcePath]stringByAppendingPathComponent:fileName];
NSArray *levelsArray = [NSArray arrayWithContentsOfFile:levelPath];
NSAssert(levelsArray, @"level no loaded");


Level *l = [[Level alloc]init];
l.coinsPerLvl = [[levelsArray objectAtIndex:levelNum][@"coinsPerLvl"] integerValue];
l.words = [[levelsArray objectAtIndex:levelNum][@"words"] integerValue];
return l;
}

sample plist screen shot

Upvotes: 0

frankfg
frankfg

Reputation: 625

you only need an intermediate variable thats represents the root dictionary and extract the level dictionary from the root dictionary, e.g:

+(instancetype)levelWithNum:(int)levelNum; {

     NSString     *levelsPlist  = [[NSBundle mainBundle] pathForResource:@"levels" ofType:@"plist"];
     NSDictionary *rootDict     = [NSDictionary dictionaryWithContentsOfFile: levelsPlist];
     NSString     *levelKey     = [NSString stringWithFormat:@"level%i", levelNum];

     NSDictionary *levelDic = rootDict[levelKey];

     NSAssert(levelDic, @"level no loaded");

     Level *l = [[Level alloc]init];
     l.coinsPerLvl = [levelDic[@"coinsPerLvl"] integerValue];
     l.words = levelDic[@"words"];
     return l;
}

Hope it help.

Upvotes: 1

Related Questions