iOS App 数据持久化
数据的持久化就是让数据能够持久的保存,实现它的方法有两种:云端和本地。本文试着简单总结本地持久化的方法。
本地持久化其实就是将数据保存到闪存,那么我们应该用什么方法保存,又应该保存在哪呢?
文件系统基础
在OS X和iOS中,文件系统处理数据文件,应用程序和操作系统本身相关文件的持久存储。下面简要介绍下 iOS 文件系统的基础知识,以便我们更好的使用她。
iOS应用和文件系统的交互基本上仅限于它沙盒内目录。新应用安装过程中,安装程序为应用创建了数个容器。每个容器有个特定的角色。The bundle container holds the app’s bundle, whereas the data container holds data for both the application and the user. The data container is further divided into a number of directories that the app can use to sort and organize its data. The app may also request access to additional containers—for example, the iCloud container—at runtime.
这些容器构成了应用文件系统的基本面。下图是应用沙盒的示意图。
iOS应用常用的目录列表:
Directory | Description |
---|---|
AppName.app | This is the app’s bundle |
Documents/ | Use this directory to store user-generated content. |
Documents/Inbox | Use this directory to access files that your app was asked to open by outside entities. |
Library/ | This is the top-level directory for any files that are not user data files. |
tmp/ | Use this directory to write temporary files that do not need to persist between launches of your app. |
数据的建议存储位置
限于篇幅,关于应用的数据应该放到哪,可以查阅File System Programming Guide > File System Basics > About the iOS File System > Where You Should Put Your App’s Files。
数据持久化的方法
- NSUserDefaults;
- Property Lists;
- Archive;
- 数据库;
- Core Data。