plist中的增量数

问题描述 投票:0回答:2

我使用下面的方法从我的plist获取一个数组,然后将某个值增加1,然后保存它。但是我记录了数组,每次实际上值并没有增加。

在我的plist中,我有一个数组,并且在这个数字值中,每个都被设置为0.因此,每次我再次运行它,它似乎回到0。

NSString *path = [[NSBundle mainBundle] bundlePath];
    NSString *finalPath = [path stringByAppendingPathComponent:@"Words.plist"];

    NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithContentsOfFile:finalPath];
    NSMutableArray *errors = [dict objectForKey:[NSString stringWithFormat:@"Errors%d.%d", [[stageSelectionTable indexPathForSelectedRow] section] +1, [[stageSelectionTable indexPathForSelectedRow] row] +1]];

    int a = [[errors objectAtIndex:wordIndexPath] intValue];
    a += 1;
    NSNumber *b = [NSNumber numberWithInt:a];
    [errors replaceObjectAtIndex:wordIndexPath withObject:b];

    [errors writeToFile:finalPath atomically:YES];
iphone objective-c arrays plist
2个回答
4
投票

您只能写入documents-folder中的文件。你不能写你的包!

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:@"Namelist.plist"];

您可以使用NSFilemanager将Plist-File复制到documents-folder。


要获取文件的路径:

- (NSString *)filePath {
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *filePath = [documentsDirectory stringByAppendingPathComponent:@"MyFile.plist"];
    return filePath;
}

要复制该文件(如果该文件不存在):

NSFileManager *fileManager = [NSFileManager defaultManager];
if (![fileManager fileExistsAtPath:[self filePath]]) {
        NSString *path = [[NSBundle mainBundle] pathForResource:@"MyFile" ofType:@"plist"];
    [fileManager copyItemAtPath:path toPath:[self filePath] error:nil];
}

现在您可以将NSDictionary写入Documents-Directory:

[dict writeToFile:[self filePath] atomically:YES];

但是你真的需要更新dict中的数组!


2
投票

您正在将数组写入磁盘,而不是数组源自的字典:

[dict writeToFile:finalPath atomically:YES];

此外,在保存之前,您需要将Errors%d.%d对象替换为更新的对象:

[dict setObject:errors forKey:/* your formatted key*/];

最后,正如@ mavrick3指出的那样,您无法将文件保存到捆绑包中,只能保存到应用程序的文档目录中。

© www.soinside.com 2019 - 2024. All rights reserved.