Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Saving NSArray to NSUserDefaults and getting it in NSMutableArray

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

like image 999
Omer Waqas Khan Avatar asked Feb 09 '12 14:02

Omer Waqas Khan


People also ask

How do I save an array in NSUserDefaults in Objective C?

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.

What is difference between NSArray and NSMutableArray?

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.

What types can you store natively in NSUserDefaults?

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.

How do you declare NSArray in Objective C?

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];


1 Answers

 [[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]; 
like image 194
Vignesh Avatar answered Sep 30 '22 12:09

Vignesh