来自 plist 的字典

Dictionary from plist

我有 3 个 plist 文件,分别命名为 level0、level1、level2,所有这些 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;
}

希望对您有所帮助。

将你的 plist root 作为一个数组(如下所示)。这样您就可以轻松获取关卡信息。

示例代码

+(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