writeToFile:atomically:不保存新的plist数据

时间:2013-05-01 18:45:21

标签: ios objective-c file-io nsfilemanager

每次启动应用时,我都会使用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文件名的拼写方式与我在代码中拼写的方式完全相同,通过Copy-Paste ) enter image description here

原始plist文件也位于目标中的“Copy Bundle Resources”中。

enter image description here

2 个答案:

答案 0 :(得分: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];

答案 1 :(得分:1)

设置数据时出错了。

你应该这样做:

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

而不是:

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