IOS:使用 NSUserDefault 存储一个数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7570708/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
IOS: store an array with NSUserDefault
提问by cyclingIsBetter
I want to store an array with NSUserDefault
, then, I put in applicationDidEnterBackground
我想用 存储一个数组NSUserDefault
,然后,我放入applicationDidEnterBackground
[[NSUserDefaults standardUserDefaults] setObject:myArray forKey:@"myArray"];
and in application didFinishLaunchingWithOption
并在 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?
对于多任务设备可以,但对于非多任务设备,我该如何解决?
回答by Jacob Relkin
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.)
将对象存储在 inNSUserDefaults
中-applicationWillTerminate:
,如果它尚未通过调用保存-applicationDidEnterBackground:
(即检查是否支持多任务处理,如果支持,则不要保存它,因为它已经保存了。)
- (void) applicationWillTerminate:(UIApplication *) app {
if([[UIDevice currentDevice] respondsToSelector:@selector(isMultitaskingSupported)] &&
![[UIDevice currentDevice] isMultitaskingSupported]) {
[[NSUserDefaults standardUserDefaults] setObject:myArray forKey:@"myArray"];
}
}
回答by Vincent
Do not forget to sync the buffer before going into background:
在进入后台之前不要忘记同步缓冲区:
[[NSUserDefaults standardUserDefaults] synchronize];
回答by fishinear
The previous answers are all correct, but note that neither applicationDidEnterBackground
nor applicationWillTerminate
are guaranteed to be called in all situations. You are usually better off storing important data whenever it has changed.
前面的答案都是正确的,但请注意,在所有情况下都applicationDidEnterBackground
不能applicationWillTerminate
保证调用。通常最好在重要数据发生变化时存储它。
回答by kv0
Save NSUserDefaults at
将 NSUserDefaults 保存在
- (void)applicationWillTerminate:(UIApplication *)application
回答by Saurabh Passolia
set
放
[[NSUserDefaults standardUserDefaults] setObject:myArray forKey:@"myArray"];
in
在
applicationWillTerminate
回答by Catalin
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
并且不要忘记在您尝试保存且包含在数组中的对象中使用 encodeWithCoder 和 initWithCoder