覆盖现有的属性列表

时间:2015-07-17 22:51:30

标签: ios nsstring nsdictionary nsbundle

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

        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方法之后,路径中的属性列表没有任何内容......

1 个答案:

答案 0 :(得分:0)

添加到主包中的文件无法修改(它们应该是完全静态的),这就是代码加载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);
}

我希望这有帮助!