ios - 来自 plist 的字典

标签 ios objective-c plist

我有 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 中读取一本字典。

感谢任何帮助!

enter image description here

最佳答案

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

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

相关文章:

objective-c - cocoa 分布式对象

xcode - Xcode 项目模板中的每个文件编译器标志

GoogleService-Info.plist 文件中的 iOS Firebase IS_ADS_ENABLED 标志

ios - 页面错误显示有一处或多处错误

ios - 在 Xcode 中测试异步方法

objective-c - 如何在 Swift 中使用 RLMArray 和 Realm for Objective-C?

iphone - 如何从 plist 加载值?

android - 我可以完全更改我的移动应用程序的基本代码并仍然保留我在 Google Play 和 Apple 商店中的下载次数吗?

ios - 如何使用 Swift 为 UITableViewCell 设置动画?

objective-c - 是否可以在 Interface Builder 中设计 NSCell 子类?