0

设置时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];  
4

1 回答 1

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];  
于 2012-08-08T20:17:38.407 回答