在plist作品中写入字典,然后从plist返回读取字典(null)

时间:2013-01-09 23:53:17

标签: nsmutablearray plist nsmutabledictionary read-write

这就是我在viewDidLoad方法中访问plist中字典的方法:

     NSString* documentsDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
     NSString *fileName = [NSString stringWithFormat:@"Level.plist"];
     filePath = [documentsDir stringByAppendingPathComponent:fileName];
     array = [[NSMutableArray alloc] initWithContentsOfFile:filePath];
     dict = [array objectAtIndex:1];

这很好用,然后我写这样的字典:

    score = [NSString stringWithFormat:@"%d", score.integerValue + 10];
    [dict setObject:score forKey:@"Score"];
    [dict writeToFile:filePath atomically: NO];

这也可以正常工作,但是一旦我返回到这个视图并尝试在viewDidLoad方法中再次访问字典,它就会为字典返回(null)。

1 个答案:

答案 0 :(得分:0)

这是因为您正在将文件作为数组读取,但是当您再次将其写回时,您只会写出字典,而不是包含该字典的数组。如果您尝试使用NSMutableArray来读取其根目录下具有除数组之外的其他内容的plist文件,那么将导致它返回nil。因此,如果您只是在最后一行代码中将dict替换为array,那么应该这样做。

相关问题