如何在NSUserDefaults中保存NSMutablearray [英] How to save NSMutablearray in NSUserDefaults
问题描述
我有两个 NSMutableArray
。它们由图像或文本组成。
数组通过 UITableView
显示。
当我杀死应用程序时, UITableView
中的数据会丢失。
如何使用 NSUserDefault
在 UITableView
中保存数组?
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
?
推荐答案
注意:NSUserDefaults将始终返回您传入的对象的不可变版本。
Note: NSUserDefaults will always return an immutable version of the object you pass in.
To存储信息:
// 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];
要检索信息:
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
NSArray *arrayOfImages = [userDefaults objectForKey:@"tableViewDataImage"];
NSArray *arrayOfText = [userDefaults objectForKey:@"tableViewDataText"];
// Use 'yourArray' to repopulate your UITableView
首次加载时,检查是否从 NSUserDefaults
返回的结果是 nil
,如果是,则需要创建数据,否则加载数据来自 NSUserDefaults
,您的 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.
更新
在Swift-3中,可以使用以下方法:
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")
这篇关于如何在NSUserDefaults中保存NSMutablearray的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!