gpt4 book ai didi

iphone - iOS - 保存到 plist

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

我正在尝试更改 plist 的值(@key“userId”,起始值为 0)

NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"GlobalSettings" ofType:@"plist"];
NSMutableDictionary *data = [NSMutableDictionary dictionaryWithContentsOfFile:plistPath];
NSDictionary *userId = [data objectForKey:@"userId"];

[data setValue:(@"99") forKey:@"userId"];
[data writeToFile:plistPath atomically: NO];

userId = [data objectForKey:@"userId"];
NSLog(@"%@", userId);

日志显示该值已更改为 99,但当我打开 plist 时,该值仍为 0

最佳答案

您不能将数据保存在应用程序的主包中,而必须像这样保存在文档目录中:

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

if([[NSFileManager defaultManager] fileExistsAtPAth:plistFilePath])
{//already exits

NSMutableDictionary *data = [NSMutableDictionary dictionaryWithContentsOfFile:plistFilePath];
NSDictionary *userId = [data objectForKey:@"userId"];
[data setValue:(@"99") forKey:@"userId"]; //new value here
[data writeToFile:plistPath atomically: YES];
userId = [data objectForKey:@"userId"];
NSLog(@"%@", userId);
}
else{ //firstly take content from plist and then write file document directory

NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"GlobalSettings" ofType:@"plist"];
NSMutableDictionary *data = [NSMutableDictionary dictionaryWithContentsOfFile:plistPath];
NSDictionary *userId = [data objectForKey:@"userId"];

[data setValue:(@"99") forKey:@"userId"];//new value here
[data writeToFile:plistFilePath atomically:YES];

userId = [data objectForKey:@"userId"];
NSLog(@"%@", userId);
}

关于iphone - iOS - 保存到 plist,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12365611/

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