如何在 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.
存储信息:
// 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屋!