无法在 NSUserDefaults 中保存 NSMutableArray
我试图在设备上保存 NSMutableArray ,但每次重新加载应用程序时,数据都会被删除。
我尝试使用 NSUserDefaults 但问题仍然存在,
这是我正在使用的代码
-(void) addingData{
[data addObject:theBarcodeString]; //data is the NSMutableArray
[mainTableView reloadData]; //this is a UITableView where the data from the NSMutableArray is populated
[self endText];
history=[NSUserDefaults standardUserDefaults];
[history setObject:data forKey:@"history" ];
}
,这是我加载数据的位置,
- (void)viewDidLoad
{
...
if (data == nil) {
data = [[NSMutableArray alloc] init]; //onload it always goes to his line
else {
data=[[NSUserDefaults standardUserDefaults] objectForKey:@"history" ];
}
...
}
我做错了什么?
I am trying to save an NSMutableArray on device , but everytime I reload the application the data is erased.
I tried to use NSUserDefaults but the problem persists
here is the code I am using
-(void) addingData{
[data addObject:theBarcodeString]; //data is the NSMutableArray
[mainTableView reloadData]; //this is a UITableView where the data from the NSMutableArray is populated
[self endText];
history=[NSUserDefaults standardUserDefaults];
[history setObject:data forKey:@"history" ];
}
and here is where I load the data
- (void)viewDidLoad
{
...
if (data == nil) {
data = [[NSMutableArray alloc] init]; //onload it always goes to his line
else {
data=[[NSUserDefaults standardUserDefaults] objectForKey:@"history" ];
}
...
}
what am I doing wrong ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您不应该测试 data == nil 是否。相反,只需执行以下操作:
请注意,您必须稍后发布它。
如果您希望
data
成为可变数组,则必须使用:如果您尝试在不使用 mutableArrayValueForKey 的情况下对数据执行变异操作,您将会崩溃,因为所有对象从 NSUserDefaults 返回的值是不可变的。
You shouldn't be testing to see if data == nil. Instead, just do:
Note that you will have to release that later.
If you want
data
to be a mutable array, you must use:If you try to performing mutating operations on data without using mutableArrayValueForKey, you will get a crash, because all objects returned from NSUserDefaults are immutable.
因此,您必须添加
[history Synchronize]
来强制写入默认值编辑:来自 文档
因此,如果您想立即保存更改,请调用
[历史同步]
。So you have to add
[history synchronize]
to force write on the defaultsEdit: From Docs
So if you want to save changes immediately call
[history synchronize]
.