【问题标题】:Dictionary from plist来自 plist 的字典
【发布时间】:2016-08-22 19:34:08
【问题描述】:

我有 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 文件的示例一样。

坦克寻求帮助!

【问题讨论】:

  • levels.plist 有什么问题?

标签: ios objective-c plist


【解决方案1】:

您只需要一个代表根字典的中间变量,并从根字典中提取级别字典,例如:

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

希望对您有所帮助。

【讨论】:

  • 谢谢!对我帮助很大!
【解决方案2】:

将您的 plist 根设为数组(如下所示)。这样您就可以轻松获得关卡信息。

示例代码

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多