gpt4 book ai didi

xml - NSUserDefaults 和 NSPropertyListSerialization

转载 作者:行者123 更新时间:2023-12-03 17:54:24 28 4
gpt4 key购买 nike

我正在使用 NSUserDefaults 编写一些首选项,尽管我想将它们保存为 XML 格式(目前默认情况下以二进制格式保存)。我见过some examples of saving .plists using NSPropertylistSerialization ,但是它们看起来过于复杂。有没有简单的方法可以做到这一点?

NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];

[defaults setObject:[NSNumber numberWithBool:NO] forKey:@"Button One"];
[defaults setObject:[NSNumber numberWithBool:NO] forKey:@"Button Two"];

[[NSUserDefaults standardUserDefaults] synchronize];

最佳答案

使用 Xcode 界面创建的

.plist 可读但不可写。如果您想对项目 bundle 中的文件进行更改,主要在要复制的文档或库中的文件夹之一中,那么始终必须处理副本或使用代码创建 .plist。

创建:

NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,   NSUserDomainMask, YES) objectAtIndex:0];
NSString* plistPath = [documentsPath stringByAppendingPathComponent:@"test.plist"];

NSArray* fruits= [NSArray arrayWithObjects:@"apple", @"orange", @"cherry", nil];
NSArray* vegetables= [NSArray arrayWithObjects:@"cabbage", @"pumpkin", @"leek", nil];

NSDictionary* dictionary= [NSDictionary dictionaryWithObjectsAndKeys:fruits, @"fruits", vegetables, @"vegetables", nil];

[dictionary writeToFile:plistPath atomically:YES];

阅读和写作:

NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,    NSUserDomainMask, YES) objectAtIndex:0];
NSString* plistPath = [documentsPath stringByAppendingPathComponent:@"test.plist"];

NSDictionary* dictionary= [[NSDictionary alloc] plistPath ];

NSMutableArray* fruits= [dictionary objectForKey:@"fruits"];
NSMutableArray* vegetables= [dictionary objectForKey:@"vegetables"];

NSLog(@"First Fruit: %@",[fruits objectAtIndex:0]);
NSLog(@"First Vegetable: %@",[vegetables objectAtIndex:0]);

[fruits replaceObjectAtIndex:0 withObject:@"banana"];

[dictionary writeToFile:plistYolu atomically:YES];

关于xml - NSUserDefaults 和 NSPropertyListSerialization,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16009187/

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