IOS:使用 NSUserDefault 存储数组
我想用 NSUserDefault
存储一个数组,然后,我放入 applicationDidEnterBackground
[[NSUserDefaults standardUserDefaults] setObject:myArray forKey:@"myArray"];
并在 application didFinishLaunchingWithOption
中,
myArray= [[NSMutableArray alloc]
initWithArray:[[NSUserDefaults standardUserDefaults]
objectForKey:@"myArray"]];
这对于多任务设备来说是可以的,但对于非 -多任务设备,我该如何解决?
I want to store an array with NSUserDefault
, then, I put in applicationDidEnterBackground
[[NSUserDefaults standardUserDefaults] setObject:myArray forKey:@"myArray"];
and in application didFinishLaunchingWithOption
myArray= [[NSMutableArray alloc]
initWithArray:[[NSUserDefaults standardUserDefaults]
objectForKey:@"myArray"]];
it's ok for multitasking device, but for not-multitasking device, how can I solve?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
如果尚未通过调用
-applicationDidEnterBackground:
保存对象,则将对象存储在-applicationWillTerminate:
的NSUserDefaults
中(即检查是否支持多任务,如果支持,则不要保存,因为它已经保存了。)Store the object in
NSUserDefaults
in-applicationWillTerminate:
, if it hasn't already been saved by the invocation of-applicationDidEnterBackground:
(i.e. check if multitasking is supported, if it is, then don't save it because it's already been saved.)不要忘记在进入后台之前同步缓冲区:
Do not forget to sync the buffer before going into background:
前面的答案都是正确的,但请注意,
applicationDidEnterBackground
和applicationWillTerminate
都不能保证在所有情况下都被调用。当重要数据发生变化时,您通常最好将其存储起来。The previous answers are all correct, but note that neither
applicationDidEnterBackground
norapplicationWillTerminate
are guaranteed to be called in all situations. You are usually better off storing important data whenever it has changed.将 NSUserDefaults 保存在
Save NSUserDefaults at
设置
在
set
in
并且不要忘记在您尝试保存且包含在数组中的对象内使用encodeWithCoder和initWithCoder
and don't forget to use the encodeWithCoder and initWithCoder inside the object that you are trying to save and that is contained in the array