Swift 2.2 .plist文件存储本地数据


代码如下
<pre>
<code>
`
import UIKit

class ViewController: UIViewController
{

override func viewDidLoad()
{
    super.viewDidLoad()
    
    //Document path   本地数据数据路径   .plist格式
    let path = NSHomeDirectory() + "/Documents"
    print("path\n\(path)")
    
    let fileManager = NSFileManager.defaultManager()
    let localDataPath = NSHomeDirectory() + "/Documents/localData.plist"
    var isLocalDataExisted = fileManager.fileExistsAtPath(localDataPath)
    
    print("isLocalDataExisted->\(isLocalDataExisted)")
    
    //判断.plist文件是否存在
    if isLocalDataExisted == false//文件不存在
    {
        fileManager.createFileAtPath(localDataPath, contents: nil, attributes: nil)//创建.plist文件
    }
    isLocalDataExisted = fileManager.fileExistsAtPath(localDataPath)
    print("isLocalDataExisted->\(isLocalDataExisted)")
    
    //设置root
    let root = NSMutableDictionary()
    //设置boolean
    root.setValue(true, forKey: "key1")
    //设置array
    root.setValue(["one","two"], forKey: "key2")
    //设置number
    root.setValue(1.2, forKey: "key3")
    //设置dictionay
    root.setValue(["key1":"value1","key2":"value2"], forKey: "key4")
    //设置date
    root.setValue(NSDate(), forKey: "key5")
    //将root写入.plist文件
    root.writeToFile(localDataPath, atomically: true)
    

    isLocalDataExisted = fileManager.fileExistsAtPath(localDataPath)
    print("isLocalDataExisted->\(isLocalDataExisted)")
    
    try! fileManager.removeItemAtPath(localDataPath)//删除本地数据文件
    
    isLocalDataExisted = fileManager.fileExistsAtPath(localDataPath)
    print("isLocalDataExisted->\(isLocalDataExisted)")
    
}

override func didReceiveMemoryWarning()
{
    super.didReceiveMemoryWarning()
}

}
`
</code>
</pre>

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容