0

writeToFile:atomically:每次启动应用程序时,我都会将 plist 中的键值更新 1 。我将这段代码放入viewDidLoad,它读取键的字符串值,获取该字符串的数值,将其增加 1,将其转换回字符串,并将其作为该键的新字符串写入,但是当我阅读它再次似乎没有更新。我无法弄清楚我做错了什么。我不需要一个特殊的框架writeToFile:atomically:,对吗?

这是代码:

NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];

NSString *path = [documentsDirectory stringByAppendingPathComponent:@"DaysLaunched.plist"];

NSFileManager *fileManager = [NSFileManager defaultManager];

if (![fileManager fileExistsAtPath: path])
{
    NSString *bundle = [[NSBundle mainBundle] pathForResource:@"DaysLaunched" ofType:@"plist"];

    [fileManager copyItemAtPath:bundle toPath:path error:&error];
}

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

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

NSString *currentNumberOfDays = [NSString stringWithFormat:@"%@",[plistDict objectForKey:@"numberOfDays"]];
NSLog(@"currentNumberOfDays = %@", currentNumberOfDays); //0

int days = [currentNumberOfDays intValue];
days ++;
currentNumberOfDays = [NSString stringWithFormat:@"%d", days];

[data1 setObject:[NSString stringWithFormat:@"numberOfDays"] forKey:currentNumberOfDays];
NSLog(@"currentNumberOfDays = %@", currentNumberOfDays); //1


[data1 writeToFile: path atomically:YES];

currentNumberOfDays = [NSString stringWithFormat:@"%@",[plistDict objectForKey:@"numberOfDays"]];
NSLog(@"currentNumberOfDays = %@", currentNumberOfDays); //0 ??????? writeToFile isn't working?

这是我的“支持文件”文件夹中“DaysLaunched.plist”的屏幕截图,(我还通过复制粘贴验证了 plist 文件名的拼写方式与我在代码中的拼写方式完全相同) 在此处输入图像描述

原始 plist 文件也在我的目标中的“复制捆绑资源”中。

在此处输入图像描述

4

2 回答 2

3

尝试

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];

NSString *path = [documentsDirectory stringByAppendingPathComponent:@"DaysLaunched.plist"];

NSFileManager *fileManager = [NSFileManager defaultManager];

if (![fileManager fileExistsAtPath: path])
{
    NSString *bundle = [[NSBundle mainBundle] pathForResource:@"DaysLaunched" 
                                                       ofType:@"plist"];
    [fileManager copyItemAtPath:bundle toPath:path error:&error];
}

NSMutableDictionary *plistDict = [NSMutableDictionary dictionaryWithContentsOfFile:path];

NSInteger days = [plistDict[@"numberOfDays"] integerValue];

plistDict[@"numberOfDays"] = [@(++days) stringValue];

[plistDict writeToFile: path atomically:YES];
于 2013-05-01T18:57:26.543 回答
1

您在设置数据时犯了一个错误。

你应该做:

[data1 setObject:currentNumberOfDays forKey:@"numberOfDays"];

代替:

[data1 setObject:[NSString stringWithFormat:@"numberOfDays"] forKey:currentNumberOfDays];
于 2013-05-01T18:56:01.893 回答