我正在使用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];
答案 0 :(得分:1)
.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];