gpt4 book ai didi

ios - 写入文件 :atomically: not saving new plist data

转载 作者:行者123 更新时间:2023-11-28 19:10:15 26 4
gpt4 key购买 nike

我正在使用 writeToFile:atomically: 每次启动应用程序时将我的 plist 中的键值更新为 1。我将这段代码放在 viewDidLoad 中,它读取键的字符串值,获取该字符串的数值,将其加 1,将其转换回字符串,并将其作为新字符串写入对于那把 key ,但当我再次阅读它时,它似乎还没有更新。我不知道我做错了什么。我不需要用于 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 文件名的拼写方式与我在代码中的拼写方式完全相同) enter image description here

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

enter image description here

最佳答案

尝试

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];

关于ios - 写入文件 :atomically: not saving new plist data,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16324349/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com