When setting NSUserDefaults
, I was initially using this code to set the defaults...
NSMutableArray *array = [NSMutableArray arrayWithObjects: @"string1", @"string2", @"string3", nil];
[[NSUserDefaults standardUserDefaults] setObject:array forKey: @"preset1"];
[[NSUserDefaults standardUserDefaults] synchronize];
I've learned that I should be using this instead:
NSMutableArray *array = [NSMutableArray arrayWithObjects: @"string1", @"string2", @"string3", nil];
NSDictionary *appDefaults = [NSDictionary dictionaryWithObject:array forKey:@"preset1"];
[[NSUserDefaults standardUserDefaults] registerDefaults:appDefaults];
Now I'm having an issue manipulating the objects later on in array
. Here is the code I use to add/remove strings from array
. It worked fine when I was initially setting the defaults manually in my first example. Now, the objects will not remove from the array. I did notice when printing the array in LLDB debugger that array
is now being stored as a NSCFArray
when it was just an NSArray
before.
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];
This code works for me with your setup, after initializing the defaults the second way you described:
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];
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.