[Xcode 实际操作]七、文件与数据-(9)编码创建Plist文件(属性列表文件)

目录:[Swift]Xcode实际操作

本文将演示如何通过编码的方式,创建属性列表文件。

在项目导航区,打开视图控制器的代码文件【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 }
原文地址:https://www.cnblogs.com/strengthen/p/10048768.html