How to save NSMutablearray in NSUserDefaults How to save NSMutablearray in NSUserDefaults objective-c objective-c

How to save NSMutablearray in NSUserDefaults


Note: NSUserDefaults will always return an immutable version of the object you pass in.

To store the information:

// Get the standardUserDefaults object, store your UITableView data array against a key, synchronize the defaultsNSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];[userDefaults setObject:arrayOfImage forKey:@"tableViewDataImage"];[userDefaults setObject:arrayOfText forKey:@"tableViewDataText"];[userDefaults synchronize];

To retrieve the information:

NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];NSArray *arrayOfImages = [userDefaults objectForKey:@"tableViewDataImage"];NSArray *arrayOfText = [userDefaults objectForKey:@"tableViewDataText"];// Use 'yourArray' to repopulate your UITableView

On first load, check whether the result that comes back from NSUserDefaults is nil, if it is, you need to create your data, otherwise load the data from NSUserDefaults and your UITableView will maintain state.

Update

In Swift-3, the following approach can be used:

let userDefaults = UserDefaults.standarduserDefaults.set(arrayOfImage, forKey:"tableViewDataImage")userDefaults.set(arrayOfText, forKey:"tableViewDataText")userDefaults.synchronize()var arrayOfImages = userDefaults.object(forKey: "tableViewDataImage")var arrayOfText = userDefaults.object(forKey: "tableViewDataText")


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.

NSMutableArray *yourArray = [[[NSUserDefaults standardUserDefaults] arrayForKey:@"YourKey"] mutableCopy];

Then you simply set the UITableview data from your mutable array via the UITableView delegate

Hope this helps!


I want just to add to the other answers that the object that you are going to store store in the NSUserDefault, as reported in the Apple documentation must be conform to this:

"The value parameter can be only property list objects: NSData, NSString, NSNumber, NSDate, NSArray, or NSDictionary. For NSArray and NSDictionary objects, their contents must be property list objects."

here the link to property list programming guide

so pay attention about what is inside your array