ios 如何在 NSUserDefaults 中保存 NSMutablearray

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19634426/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 02:38:28  来源:igfitidea点击:

How to save NSMutablearray in NSUserDefaults

iosobjective-cuitableviewnsmutablearraynsuserdefaults

提问by user2841148

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 UITableViewgets lost. How to save array in UITableViewby using NSUserDefault?

我有两个NSMutableArray。它们由图像或文本组成。数组通过UITableView. 当我杀死应用程序时,其中的数据UITableView会丢失。如何保存在阵列UITableView使用NSUserDefault

回答by Tim

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 NSUserDefaultsis nil, if it is, you need to create your data, otherwise load the data from NSUserDefaultsand your UITableViewwill maintain state.

在第一次加载时,检查返回的结果是否NSUserDefaultsnil,如果是,则需要创建数据,否则加载数据NSUserDefaultsUITableView保持状态。

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

回答by Philipp Otto

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 UITableviewdata from your mutable array via the UITableViewdelegate

然后您只需UITableview通过UITableView委托设置可变数组中的数据

Hope this helps!

希望这可以帮助!

回答by Manu

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

“值参数可以是唯一的财产清单对象:NSDataNSStringNSNumber,,的NSDate,NSArray的,或者NSDictionary的NSArray的对于和的NSDictionary对象,它们的内容必须属性列表对象。”

here the link to property list programming guide

这里是属性列表编程指南的链接

so pay attention about what is inside your array

所以要注意你的数组里面有什么

回答by A.G

Save:

节省:

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

Retrieve:

取回:

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

回答by Ugo Marinelli

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

}

回答by Dilip Tiwari

Save information of Array in NSUserdefaultswith key.

NSUserdefaults用key保存Array的信息。

"MutableArray received from JSON response"

“从 JSON 响应收到的 MutableArray”

[[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.

这对我的项目有帮助,希望对某人有所帮助。

回答by aironik

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 NSUserDefaultsyou can store only simply objects like NSString, NSDictionary, NSNumber, NSArray.

NSUserDefaults您只能存储简单的对象,如NSString, NSDictionary, NSNumber, NSArray

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

您也可以序列化NSKeyedArchiver/NSKeyedUnarchiver符合 NSCoding 协议的对象。

回答by Lance

If you need to add strings to the NSMutableArrayin ant specific order, or if you are using the NSMutableArrayfor a UITableViewyou may want to use this instead:

如果您需要将字符串添加到NSMutableArrayant 特定的顺序,或者如果您使用的是NSMutableArrayfor a,UITableView您可能想要使用它:

[NSMutableArray insertObject:string atIndex:0];

回答by Mughees

Swift Version:

迅捷版:

Save Array in NSUserDefaults:

在 NSUserDefaults 中保存数组:

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

Retrieve Bool Array From NSUserDefaults:

从 NSUserDefaults 检索布尔数组:

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]()
    }