plist是一個XML的子集,使用UTF-8編碼的文本文件,它的根節點是一個字典,內容由多個主鍵和值構成。經常用來存儲App的配置信息。javascript
能夠直接使用NSDictionary類直接存儲它的內容到plist內,好比這樣:java
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window : UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
window = UIWindow()
window!.rootViewController = Page()
window!.rootViewController!.view.backgroundColor = .blue
window!.makeKeyAndVisible()
return true
}
}
class Page: UIViewController {
let filename = "/profile.plist"
let data:[String:String] = ["key1" : "value1", "key2":"value2", "key3":"value3"]
override func viewDidLoad() {
super.viewDidLoad()
bar()
}
func bar(){
do {
let documentDirectory = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as String
let path = "\(documentDirectory)/\(filename)"
print(path)
let dict = NSDictionary(dictionary: data)
let isWritten = dict.write(toFile: path, atomically: true)
let dict1 = NSDictionary(contentsOfFile: path)
print(dict1)
print("file created: \(isWritten)")
let text = try String(contentsOfFile: path, encoding: String.Encoding.utf8)
print(text)
}catch {print("\(error)")}
}
}複製代碼
類NSDictionary的方法write能夠指定文件名,而後寫入到指定文件。初始化方法 NSDictionary(contentsOfFile:)能夠讀取plist到詞典對象內。數組
由於plist是UTF-8編碼的文本文件,因此,能夠使用String打開此文件,輸出內容以下(去掉主題無關的文件頭後):app
<plist version="1.0">
<dict> <key>key1</key> <string>value1</string> <key>key2</key> <string>value2</string> <key>key3</key> <string>value3</string> </dict>
</plist>複製代碼
做爲鍵值對的值,不單單但是是字符串,還能夠是數字、日期、數組和詞典。以下案例展現了plist存儲的更多可能性:ide
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window : UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
window = UIWindow()
window!.rootViewController = Page()
window!.rootViewController!.view.backgroundColor = .blue
window!.makeKeyAndVisible()
return true
}
}
class Page: UIViewController {
let filename = "/profile.plist"
let data:[String:Any] = ["key1" : "value1", "key2":["key11":"value11"], "key3":[1,"2",NSDate(),3.1]]
override func viewDidLoad() {
super.viewDidLoad()
bar()
}
func bar(){
do {
let documentDirectory = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as String
let path = "\(documentDirectory)/\(filename)"
print(path)
let dict = NSDictionary(dictionary: data)
let isWritten = dict.write(toFile: path, atomically: true)
let dict1 = NSDictionary(contentsOfFile: path)
print(dict1)
print("file created: \(isWritten)")
let text = try String(contentsOfFile: path, encoding: String.Encoding.utf8)
print(text)
}catch {print("\(error)")}
}
}
7673複製代碼