0

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

NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];

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

[[NSUserDefaults standardUserDefaults] synchronize];
4

1 回答 1

1

您使用 Xcode 接口创建的 .plist 可读但不可写。如果您想更改项目 Bundle 中的文件,主要是在 Documents 或 Library 中的一个文件夹中进行复制,然后总是需要处理副本或使用代码创建 .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];
于 2013-04-15T07:16:26.087 回答