覆盖现有的 属性 列表

Override an existed Property List

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

        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 方法之后,我的 属性 列表没有任何反应...

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

您实际上并没有注意到写入操作失败,因为您没有检查其结果。 (- writeToFile:atomically: 实际上 returns 一个 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);
}

希望对您有所帮助!