代碼如下
<pre>
<code>
`
import UIKit
class ViewController: UIViewController
{
override func viewDidLoad()
{
super.viewDidLoad()
//Document path 本地?cái)?shù)據(jù)數(shù)據(jù)路徑 .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)//創(chuàng)建.plist文件
}
isLocalDataExisted = fileManager.fileExistsAtPath(localDataPath)
print("isLocalDataExisted->\(isLocalDataExisted)")
//設(shè)置root
let root = NSMutableDictionary()
//設(shè)置boolean
root.setValue(true, forKey: "key1")
//設(shè)置array
root.setValue(["one","two"], forKey: "key2")
//設(shè)置number
root.setValue(1.2, forKey: "key3")
//設(shè)置dictionay
root.setValue(["key1":"value1","key2":"value2"], forKey: "key4")
//設(shè)置date
root.setValue(NSDate(), forKey: "key5")
//將root寫入.plist文件
root.writeToFile(localDataPath, atomically: true)
isLocalDataExisted = fileManager.fileExistsAtPath(localDataPath)
print("isLocalDataExisted->\(isLocalDataExisted)")
try! fileManager.removeItemAtPath(localDataPath)//刪除本地?cái)?shù)據(jù)文件
isLocalDataExisted = fileManager.fileExistsAtPath(localDataPath)
print("isLocalDataExisted->\(isLocalDataExisted)")
}
override func didReceiveMemoryWarning()
{
super.didReceiveMemoryWarning()
}
}
`
</code>
</pre>