设置NSUserDefaults
时,我最初使用此代码设置默认值...
NSMutableArray *array = [NSMutableArray arrayWithObjects: @"string1", @"string2", @"string3", nil];
[[NSUserDefaults standardUserDefaults] setObject:array forKey: @"preset1"];
[[NSUserDefaults standardUserDefaults] synchronize];
我已经知道我应该使用它:
NSMutableArray *array = [NSMutableArray arrayWithObjects: @"string1", @"string2", @"string3", nil];
NSDictionary *appDefaults = [NSDictionary dictionaryWithObject:array forKey:@"preset1"];
[[NSUserDefaults standardUserDefaults] registerDefaults:appDefaults];
现在我遇到了array
中稍后操纵对象的问题。这是我用来添加/删除array
字符串的代码。当我在第一个示例中手动设置默认值时,它工作正常。现在,对象不会从数组中删除。在LLDB调试器中打印数组时,我注意到array
现在只在NSCFArray
之前存储为NSArray
。
NSMutableArray *array = [[NSMutableArray alloc] init];
[array addObjectsFromArray:[[NSUserDefaults standardUserDefaults] objectForKey:@"preset1"]];
NSArray *stringsToRemove = @[@"string1", @"string2" ];
for (NSUInteger i = 0; i < stringsToRemove.count; i++) {
[array removeObjectIdenticalTo:[stringsToRemove objectAtIndex:i]];
}
[[NSUserDefaults standardUserDefaults] setObject:array forKey: @"preset1"];
[[NSUserDefaults standardUserDefaults] synchronize];
答案 0 :(得分:1)
在您按照描述的第二种方式初始化默认值后,此代码适用于您的设置:
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSMutableArray *array = [[NSMutableArray alloc] initWithArray: [defaults objectForKey:@"preset1"]];
NSArray *stringsToRemove = [NSArray arrayWithObjects:@"string1", @"string2", nil];
for (NSString *aString in stringsToRemove) {
[array removeObjectIdenticalTo:aString];
}
[defaults setObject:array forKey: @"preset1"];
[defaults synchronize];