如果应用程序在 10 秒内被杀死,NSUserDefaults 将丢失新保存的数据 [英] NSUserDefaults Lose Newly Saved Data if App Killed Within 10 Seconds

查看:24
本文介绍了如果应用程序在 10 秒内被杀死,NSUserDefaults 将丢失新保存的数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种比 NSUserDefaults 更快的方法来保存用户首选项.我发现如果应用在写入 NSUserDefaults 后大约 10 秒内被杀死,它不会被永久保存.我使用默认值来保存自定义铃声的路径、自定义图像的路径、地图坐标,以及基本上只是用户定义的首选项.使用核心数据是更好的选择吗?SQLite?什么是公认的最快和最轻量级的?

I'm looking for a faster way to save user preferences than the NSUserDefaults. I've found that if the app is killed within around 10 seconds of writing to NSUserDefaults, it will not be saved permanently. I use the defaults to save paths to custom ring tones, paths to custom images, map coordinates, and basically just user defined preferences. Is using core data the better option? SQLite? What's accepted as the fastest and most lightweight?

推荐答案

一定要调用synchronize立即保存数据.

You need to be sure to call synchronize to save the data immediately.

[[NSUserDefaults standardUserDefaults] synchronize];

来自 Apple 的 类参考:

From Apple's class reference:

因为这个方法会定期自动调用,仅当您不能等待自动同步(例如,如果您的应用程序即将退出)或如果你想更新用户默认为磁盘上的内容,即使您没有进行任何更改.

Because this method is automatically invoked at periodic intervals, use this method only if you cannot wait for the automatic synchronization (for example, if your application is about to exit) or if you want to update the user defaults to what is on disk even though you have not made any changes.

回答您的第二个问题,这实际上取决于您要存储多少数据.NSUserDefaults 旨在存储非常少量的数据(用于首选项),例如切换开关的状态等.您可以在此处存储图像和铃声的路径,但这并不完全可取.我的意思是你可以,但可能不应该.

And to answer your second question, it really depends on how much data you want to store. NSUserDefaults is designed to store very small amounts of data (for preferences) like the state of a toggle switch, etc. You can get away with storing the paths to images and ring tones here but it isn't exactly advisable. By that I mean you can, but probably shouldn't.

如果您计划存储许多这样的路径,Core Data 是一种更好的方法,因为它非常可扩展且性能非常好.所以总的来说,如果你需要存储大量数据,用户核心数据,或者作为另一种选择,将路径存储在文档目录的 plist 中.

Core Data is a much better approach if you plan on storing many of these paths as it is very scalable and performs very well. So overall, if you need to store a lot of data, user Core Data, or as another alternative store the paths in a plist in the documents directory.

这篇关于如果应用程序在 10 秒内被杀死,NSUserDefaults 将丢失新保存的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆