【问题标题】:Override an existed Property List覆盖现有的属性列表
【发布时间】:2015-07-17 22:51:29
【问题描述】:

我想用特定的字典覆盖属性列表。

        NSDictionary *plist = [[NSDictionary alloc]initWithContentsOfURL:url];

        NSString *path = [[NSBundle mainBundle] pathForResource:@"Routes" ofType:@"plist"];

        NSMutableDictionary *lastDict = [[NSMutableDictionary alloc] initWithContentsOfFile:path];

        [lastDict setValue:[plist objectForKey:@"Routes"] forKey:@"Routes"];

        [lastDict writeToFile:path atomically:YES];

PS:plist(字典没问题)但是在 writeToFile 方法之后,我的属性列表从路径中没有发生任何事情......

【问题讨论】:

  • 您需要更详细地解释问题所在,并包含错误日志(使用返回错误的 API)和字典的内容。
  • 您无法更改应用程序包中包含的 plist - 这是一个只读包。首次运行应用程序时,您需要将 plist 复制到您的文档目录 - 然后您可以保存更改

标签: ios nsstring nsdictionary nsbundle


【解决方案1】:

添加到主包的文件无法修改(它们应该是完全静态的),这就是代码将加载 plist 文件但无法覆盖它的原因。

您实际上并没有注意到写入操作失败,因为您没有检查其结果。 (- writeToFile:atomically: 实际上会返回一个BOOL,告诉您操作是否成功完成。)

如果你想要一个可以动态编辑的 plist 文件,你应该将它添加到你的应用程序的文件夹中。这里有一些示例代码,展示了如何在 Documents 中创建和编辑 plist 文件的基础知识。

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

NSString *plistPath = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"simple.plist"];

NSFileManager *fileManager = [NSFileManager defaultManager];

BOOL fileExists = [fileManager fileExistsAtPath:plistPath];
if (!fileExists) {
    // The plist file does not exist yet so you have to create it
    NSLog(@"The .plist file exists");

    // Create a dictionary that represents the data you want to save
    NSDictionary *plist = @{ @"key": @"value" };

    // Write the dictionary to disk
    [plist writeToFile:plistPath atomically:YES];

    NSLog(@"%@", plist);
} else {
    // The .plist file exists so you can do interesting stuff
    NSLog(@"The .plist file exists");

    // Start by loading it into memory
    NSMutableDictionary *plist = [[NSMutableDictionary alloc] initWithContentsOfFile:plistPath];

    NSLog(@"%@", plist);

    // Edit something
    [plist setValue:@"something" forKey:@"key"];

    // Save it back
    [plist writeToFile:plistPath atomically:YES];

    NSLog(@"%@", plist);
}

我希望这会有所帮助!

【讨论】:

    猜你喜欢
    • 2020-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-19
    • 1970-01-01
    • 2019-11-27
    相关资源
    最近更新 更多