简体   繁体   English

如何在NSUserDefaults中保存NSMutablearray

[英]How to save NSMutablearray in NSUserDefaults

I have two NSMutableArray 's. 我有两个NSMutableArray They consist of images or text. 它们由图像或文本组成。 The arrays are displayed via a UITableView . 数组通过UITableView显示。 When I kill the app the data within the UITableView gets lost. 当我杀死应用程序时, UITableView的数据会丢失。 How to save array in UITableView by using NSUserDefault ? 如何使用NSUserDefaultUITableView保存数组?

Note: NSUserDefaults will always return an immutable version of the object you pass in. 注意:NSUserDefaults将始终返回您传入的对象的不可变版本。

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. 首次加载时,检查NSUserDefaults返回的结果是否为nil ,如果是,则需要创建数据,否则从NSUserDefaults加载数据, UITableView将保持状态。

Update 更新

In Swift-3, the following approach can be used: 在Swift-3中,可以使用以下方法:

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")

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 然后,您只需通过UITableView委托从可变数组中设置UITableview数据

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: 我想只是添加其他答案,你要存储的对象存储在NSUserDefault ,如Apple文档中所报告的那样必须符合以下要求:

"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." “value参数只能是属性列表对象: NSDataNSStringNSNumber ,NSDate,NSArray或NSDictionary。对于NSArray和NSDictionary对象,它们的内容必须是属性列表对象。”

here the link to property list programming guide 这里是属性列表编程指南的链接

so pay attention about what is inside your array 所以要注意阵列里面的内容

Save: 保存:

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

Retrieve: 检索:

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

Do you really want to store images in property list? 你真的想把图像存储在属性列表中吗? You can save images into files and store filename as value in NSDictionary . 您可以将图像保存到文件中,并将文件名存储为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]];
}

And you can store path or indexes in NSMutableDictionary 您可以在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;
}

In NSUserDefaults you can store only simply objects like NSString , NSDictionary , NSNumber , NSArray . NSUserDefaults您只能存储NSStringNSDictionaryNSNumberNSArray

Also you can serialize objects with NSKeyedArchiver/NSKeyedUnarchiver that conforms to NSCoding protocol . 您还可以使用符合NSCoding协议的NSKeyedArchiver/NSKeyedUnarchiver序列化对象。

如果你需要以特定的顺序将字符串添加到NSMutableArray ,或者如果你使用NSMutableArray作为UITableView你可能想要使用它:

[NSMutableArray insertObject:string atIndex:0];

In Swift 3, for an NSMutableArray, you will need to encode/decode your array to be able to save it/ retrieve it in NSUserDefaults : 在Swift 3中,对于NSMutableArray,您需要对数组进行编码/解码,以便能够在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")

}

Save information of Array in NSUserdefaults with key. 使用密钥保存NSUserdefaults中Array的信息。

"MutableArray received from JSON response" “MutableArray从JSON响应中收到”

[[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. 这帮助了我的项目并希望,它会帮助别人。

Swift Version: Swift版本:

Save Array in NSUserDefaults: 在NSUserDefaults中保存数组:

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

Retrieve Bool Array From NSUserDefaults: 从NSUserDefaults检索Bool数组:

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

Retrieve String Array From NSUserDefaults: 从NSUserDefaults检索字符串数组:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM