Dmitriy Babinskiy Dmitriy Babinskiy - 3 months ago 9
iOS Question

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

Answer

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.