1. 程式人生 > >[Xcode10 實際操作]七、檔案與資料-(9)編碼建立Plist檔案(屬性列表檔案)

[Xcode10 實際操作]七、檔案與資料-(9)編碼建立Plist檔案(屬性列表檔案)

本文將演示如何通過編碼的方式,建立屬性列表檔案。

在專案導航區,開啟檢視控制器的程式碼檔案【ViewController.swift】

 1 import UIKit
 2 
 3 class ViewController: UIViewController {
 4 
 5     override func viewDidLoad() {
 6         super.viewDidLoad()
 7         // Do any additional setup after loading the view, typically from a nib.
 8
9 //初始化一個可變字典物件,作為屬性列表內容的容器 10 let dic:NSMutableDictionary = NSMutableDictionary() 11 //設定屬性列表檔案的內容,即新增一對鍵值對。 12 dic.setObject("Bruce", forKey: "Name" as NSCopying) 13 //繼續新增屬性列表檔案的鍵值物件 14 dic.setObject("22", forKey: "Age" as NSCopying) 15 16
//生成屬性列表檔案在專案中的儲存路徑 17 let plistPath = NSHomeDirectory() + "/Documents/demoPlist.plist" 18 //將可變字典物件,寫入到指定位置的屬性列表檔案 19 dic.write(toFile: plistPath, atomically: true) 20 21 //讀取並顯示上面程式碼儲存的屬性列表檔案 22 23 //載入屬性列表檔案,並轉換為可變字典物件 24 let data:NSMutableDictionary = NSMutableDictionary.init(contentsOfFile: plistPath)! 25
//將字典物件,轉換為字串物件 26 let message = data.description 27 28 //在控制檯列印輸出,屬性列表檔案中的各項鍵值 29 print(message) 30 } 31 32 override func didReceiveMemoryWarning() { 33 super.didReceiveMemoryWarning() 34 // Dispose of any resources that can be recreated. 35 } 36 }