我有 3 个名为 level0、level1、level2 的 plist 文件,所有这些 plist 都具有相同的结构,它由数字变量和数组组成。我用这个 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;
}
现在我决定只使用一个 plist 并在其中添加 3 个字典。我怎样才能像上面使用 plist 文件的例子那样只从 plist 中读取一本字典。
感谢任何帮助!
最佳答案
你只需要一个代表根字典的中间变量,并从根字典中提取级别字典,例如:
+(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;
}
希望对您有所帮助。
关于ios - 来自 plist 的字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39071155/