将 NSMutableArray 保存到 NSUserDefaults [英] Saving NSMutableArray to NSUserDefaults
问题描述
我的 AppDelegate
中有一个 NSMutableArray
,我正在尝试将它保存到 NSUserDefaults
.NSMutableArray
(strainsfinal) 包含一个收藏项列表.我希望这个列表能够保存,即使应用程序关闭,然后重新启动也能出现.有谁知道为什么我的代码不起作用(不保存我的数据)?见下文:
I have an NSMutableArray
inside of my AppDelegate
, and I'm attempting to save it to NSUserDefaults
. The NSMutableArray
(strainsfinal) contains a list of favorited items. I want this list to save, and be present even if the app is shut down, and then restarted. Does anyone know why my code isn't working (not saving my data)? See below:
AppDelegate.m
-(void)updateStrains:(NSDictionary *)item
{
NSUserDefaults *currentDefaults = [NSUserDefaults standardUserDefaults];
NSData *dataSave = [currentDefaults objectForKey:@"strains"];
if (strainsfinal != nil)
{
NSArray *oldSavedArray = [NSKeyedUnarchiver unarchiveObjectWithData:dataSave];
if (oldSavedArray != nil)
strainsfinal = [[NSMutableArray alloc] initWithArray:oldSavedArray];
else
strainsfinal = [[NSMutableArray alloc] init];
}
}
Appdelegate.m 所以我已经将上面的方法更改为下面的方法(我认为它应该可以工作),但是应用程序崩溃了,说:终止应用程序到期未捕获的异常 'NSInvalidArguementException',原因:'NSConcreteAttributedString initwithString: nil 'value'.
Appdelegate.m So I've changed my above method to the method below (and I thought it should work), but the app crashes, saying: "Terminating app due to uncaught exception 'NSInvalidArguementException', reason: 'NSConcreteAttributedString initwithString: nil 'value'.
我错过了什么?!
-(void)updateStrains:(NSDictionary *)item {
NSData *dataSave = [NSKeyedArchiver archivedDataWithRootObject:strainsfinal];
[[NSUserDefaults standardUserDefaults] setObject:dataSave forKey:@"strains"];
NSNotificationCenter* nc = [NSNotificationCenter defaultCenter];
[nc postNotificationName:@"arrayupdated" object:self userInfo:nil];
NSLog(@"updated strains %@",strainsfinal);
}
推荐答案
必须添加
[currentDefaults synchronize];
每次将内容保存到 userDefaults 后;
each time after you save something to userDefaults;
但对于此类数据,最好使用 .plist 文件.查看文档了解更多信息.
But for such kind of data is better to use .plist files. Check documentation for more info.
编辑代码:
-(void)updateStrains:(NSDictionary *)item {
NSData *dataSave = [NSKeyedArchiver archivedDataWithRootObject:item[@"strainsfinal"]];
[[NSUserDefaults standardUserDefaults] setObject:dataSave forKey:@"strains"];
// NSNotificationCenter* nc = [NSNotificationCenter defaultCenter];
// [nc postNotificationName:@"arrayupdated" object:self userInfo:nil];
NSLog(@"updated strains %@",strainsfinal);
[[NSUserDefaults standardUserDefaults] synchronize]; // this will save you UserDefaults
}
这篇关于将 NSMutableArray 保存到 NSUserDefaults的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!