Swift开发iOS Developer

Swift数据储存方式:不同目录的使用、Plist存储数据、Us

2017-01-09  本文已影响711人  五九楼

本文主要内容

  1. iOS沙盒的目录结构
  2. 使用plist文件存储
  3. 使用NSUserDefaults存储数据

目录结构

1. Home目录。

每个应用程序都有对应的私有目录,其根目录为Home目录。该目录下又三个文件夹:Documents、Library、tmp。

iOS目录结构.png

2.Documents/Library/tmp目录使用对比

每个目录都有特定的使用方式和起行为特点,根据不同的需要进行数据的存放。


不同目录的对比

3.应用升级时的数据处理

应用更新时,涉及原应用目录文件的迁移,这也是大家比较关心的。扒了下网络上过关于iOS应用升级时的文件数据处理过程,原文如下:

Files Saved During Application Updates When a user downloads an application update, iTunes installs the update in a new application directory. It then moves the user’s data files from the old installation over to the new application directory before deleting the old installation. Files in the following directories are guaranteed to be preserved during the update process:

  • Application_Home/Documents_
  • Application_Home/Library_
    Although files in other user directories may also be moved over, you should not rely on them being present after an update.

粗略翻译下:
当用户下在应用更新版本是,iTunes会在一个新应用目录下安装升级版,之后会把用户数据从旧应用移动新应用目录下,完成后才删除旧应用。以下文件目录在应用升级时确保会保存下来:1.Documents目录。2.Library目录。虽然其他文件目录下的文件可能也会迁移过去,但并不能指望升级后一定能展示这些数据。

4.各目录获取(代码)

//Home目录获取方式
let homePath = NSHomeDirectory( )

//Documents目录获取方式
let doucumentPath = NSHomeDirectory( ) + "/Documents"

//Library目录获取方式
let libraryPath2 = NSHomeDirectory() + "/Library"

//Preferences目录一般不直接使用,而是用NSUserDefaults来创建偏好文件

//Caches目录获取方式
let cachePath = NSHomeDirectory() + "/Library/Caches"

//tmp目录的获取方式
let tmpDirectory = NSHomeDirectory() + "/tmp"

关于目录获取,我自己写了个的扩展,只要在需要获取目录路径的类中遵循SaveDataDoucumentPath协议就可以用扩展实现中的方法快速获取对应路径。

protocol SaveDataDocumentPath {
}

extension SaveDataDocumentPath {
    func HomePath() -> String {
        return NSHomeDirectory()
    }
    func DocumentsPath() -> String {
        return HomePath() + "/Documents"
    }
    func LibraryPath() -> String {
        return HomePath() + "/Library"
    }
    func tmpPath() -> String {
        return HomePath() + "/tmp"
    }
    func PreferencesPath() -> String {
        return LibraryPath() + "/Preferences"
    }
    func CachesPath() -> String {
        return LibraryPath() + "/Caches"
    }
}

plist文件的使用

文件内容

NSUserDefaults

上一篇 下一篇

猜你喜欢

热点阅读