How to save NSMutablearray in NSUserDefaults

IosObjective CUitableviewNsmutablearrayNsuserdefaults

Ios Problem Overview


I have two NSMutableArray's. They consist of images or text. The arrays are displayed via a UITableView. When I kill the app the data within the UITableView gets lost. How to save array in UITableView by using NSUserDefault?

Ios Solutions


Solution 1 - Ios

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 defaults
NSUserDefaults *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.standard

userDefaults.set(arrayOfImage, forKey:"tableViewDataImage")
userDefaults.set(arrayOfText, forKey:"tableViewDataText")
userDefaults.synchronize()

var arrayOfImages = userDefaults.object(forKey: "tableViewDataImage")
var arrayOfText = userDefaults.object(forKey: "tableViewDataText")

Solution 2 - Ios

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!

Solution 3 - Ios

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

Solution 4 - Ios

Do you really want to store images in property list? You can save images into files and store filename as value in NSDictionary.

define path for store files


NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
self.basePath = [paths firstObject];

Store and load image:







(NSString *)imageWithKey:(NSString)key {
NSString *fileName = [NSString stringWithFormat:@"%@.png", key]
return [self.basePath stringByAppendingPathComponent:fileName];
}






(void)saveImage:(UIImage *)image withKey:(NSString)key {
NSData *imageData = UIImagePNGRepresentation(image);
[imageData writeToFile:[self imageWithKey:key] atomically:YES];
}






(UIImage *)loadImageWithKey:(NSString)key { {
return [UIImage imageWithContentsOfFile:[self imageWithKey:key]];
}
  • (NSString *)imageWithKey:(NSString)key { NSString *fileName = [NSString stringWithFormat:@"%@.png", key] return [self.basePath stringByAppendingPathComponent:fileName]; }

  • (void)saveImage:(UIImage *)image withKey:(NSString)key { NSData *imageData = UIImagePNGRepresentation(image); [imageData writeToFile:[self imageWithKey:key] atomically:YES]; }

  • (UIImage *)loadImageWithKey:(NSString)key { { return [UIImage imageWithContentsOfFile:[self imageWithKey:key]]; }

And you can store path or indexes in NSMutableDictionary







(void)saveDictionary:(NSDictionary *)dictionary {
NSMutableDictionary *dictForSave = [@{ } mutableCopy];
for (NSString *key in [dictionary allKeys]) {
[self saveImageWithKey:key];
dictForSave[key] = @{ @"image" : key };
}
[[NSUserDefaults standardUserDefaults] setObject:dictForSave forKey:@"MyDict"];
}






(NSMutableDictionary *)loadDictionary:(NSDictionary *)dictionary {
NSDictionary *loadedDict = [[NSUserDefaults standardUserDefaults] objectForKey:@"MyDict"];
NSMutableDictionary *result = [@{ } mutableCopy];
for (NSString *key in [loadedDict allKeys]) {
result[key] = [self imageWithKey:key];
}
return result;
}
  • (void)saveDictionary:(NSDictionary *)dictionary { NSMutableDictionary *dictForSave = [@{ } mutableCopy]; for (NSString *key in [dictionary allKeys]) { [self saveImageWithKey:key]; dictForSave[key] = @{ @"image" : key }; } [[NSUserDefaults standardUserDefaults] setObject:dictForSave forKey:@"MyDict"]; }

  • (NSMutableDictionary *)loadDictionary:(NSDictionary *)dictionary { NSDictionary *loadedDict = [[NSUserDefaults standardUserDefaults] objectForKey:@"MyDict"]; NSMutableDictionary *result = [@{ } mutableCopy]; for (NSString *key in [loadedDict allKeys]) { result[key] = [self imageWithKey:key]; } return result; }

In NSUserDefaults you can store only simply objects like NSString, NSDictionary, NSNumber, NSArray.

Also you can serialize objects with NSKeyedArchiver/NSKeyedUnarchiver that conforms to NSCoding protocol .

Solution 5 - Ios

Save:

NSUserDefaults.standardUserDefaults().setObject(PickedArray, forKey: "myArray")
 NSUserDefaults.standardUserDefaults().synchronize()

Retrieve:

if let PickedArray = NSUserDefaults.standardUserDefaults().stringForKey("myArray") {
    print("SUCCCESS:")
    println(PickedArray)
}

Solution 6 - Ios

If you need to add strings to the NSMutableArray in ant specific order, or if you are using the NSMutableArray for a UITableView you may want to use this instead:

[NSMutableArray insertObject:string atIndex:0];

Solution 7 - Ios

In Swift 3, for an NSMutableArray, you will need to encode/decode your array to be able to save it/ retrieve it in NSUserDefaults :

Saving

//Encoding array
let encodedArray : NSData = NSKeyedArchiver.archivedData(withRootObject: myMutableArray) as NSData

//Saving
let defaults = UserDefaults.standard
defaults.setValue(encodedArray, forKey:"myKey")
defaults.synchronize()

Retrieving

//Getting user defaults
let defaults = UserDefaults.standard
    
//Checking if the data exists
if defaults.data(forKey: "myKey") != nil {
   //Getting Encoded Array
   let encodedArray = defaults.data(forKey: "myKey")
        
   //Decoding the Array
   let decodedArray = NSKeyedUnarchiver.unarchiveObject(with: encodedArray!) as! [String]
}

Removing

//Getting user defaults
let defaults = UserDefaults.standard
        
//Checking if the data exists
if defaults.data(forKey: "myKey") != nil {
           
    //Removing the Data
    defaults.removeObject(forKey: "myKey")

}

Solution 8 - Ios

Save information of Array in NSUserdefaults with key.

"MutableArray received from JSON response"

[[NSUserDefaults standardUserDefaults] setObject:statuses forKey:@"arrayListing"];

"Retrieve this information(Array) anywhere in the project with same key"

NSArray *arrayList = [[NSUserDefaults standardUserDefaults] valueForKey:@"arrayListing"];

This helped me in my project and hope, it will help someone.

Solution 9 - Ios

Swift Version:

Save Array in NSUserDefaults:

NSUserDefaults.standardUserDefaults().setObject(selection, forKey: "genderFiltersSelection")

Retrieve Bool Array From NSUserDefaults:

if NSUserDefaults.standardUserDefaults().objectForKey("genderFiltersSelection") != nil{
                selection = NSUserDefaults.standardUserDefaults().objectForKey("genderFiltersSelection") as? [Bool] ?? [Bool]()
   }

Retrieve String Array From NSUserDefaults:

if NSUserDefaults.standardUserDefaults().objectForKey("genderFiltersSelection") != nil{
                selection = NSUserDefaults.standardUserDefaults().objectForKey("genderFiltersSelection") as? [String] ?? [String]()
    }

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser2841148View Question on Stackoverflow
Solution 1 - IosTimView Answer on Stackoverflow
Solution 2 - IosPhilipp OttoView Answer on Stackoverflow
Solution 3 - IosManuView Answer on Stackoverflow
Solution 4 - IosaironikView Answer on Stackoverflow
Solution 5 - IosAlvin GeorgeView Answer on Stackoverflow
Solution 6 - IosLanceView Answer on Stackoverflow
Solution 7 - IosUgo MarinelliView Answer on Stackoverflow
Solution 8 - IosDilip TiwariView Answer on Stackoverflow
Solution 9 - IosMugheesView Answer on Stackoverflow