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

作者: 果啤 | 来源:发表于2016-05-16 15:42 被阅读1354次

    代码如下
    <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>

    相关文章

      网友评论

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

        本文链接:https://www.haomeiwen.com/subject/rrubrttx.html