How can I save NSArray
in NSUserDefaults
and then load it back in an NSMutableArray
to populate the UIPickerView
?
Also the issue is that new values would be added to that NSMutableArray
and then that array will be converted to NSArray
to be saved in NSUserDefaults
(as NSMutableArray
can't be saved in NSUserDefaults
).
Any help appreciated..
Thanks
You can save your mutable array like this: [[NSUserDefaults standardUserDefaults] setObject:yourArray forKey:@"YourKey"]; [[NSUserDefaults standardUserDefaults] synchronize]; Later you get the mutable array back from user defaults. It is important that you get the mutable copy if you want to edit the array later.
The primary difference between NSArray and NSMutableArray is that a mutable array can be changed/modified after it has been allocated and initialized, whereas an immutable array, NSArray , cannot.
Storing Default Objects The NSUserDefaults class provides convenience methods for accessing common types such as floats, doubles, integers, Boolean values, and URLs. These methods are described in Setting Default Values.
In Objective-C, the compiler generates code that makes an underlying call to the init(objects:count:) method. id objects[] = { someObject, @"Hello, World!", @42 }; NSUInteger count = sizeof(objects) / sizeof(id); NSArray *array = [NSArray arrayWithObjects:objects count:count];
[[NSUserDefaults standardUserDefaults] setObject:yourMutableArray forKey:@"Key"];
A mutable array can be stored since it is a subclass of NSArray.
To get the value as an NSMutableArray:
NSMutableArray *array = [NSMutableArray arrayWithArray:[[NSUserDefaults standardUserDefaults] objectForKey:@"Key"]];
or
NSMutableArray *array = [[[NSUserDefaults standardUserDefaults] objectForKey:@"Key"] mutableCopy];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With