Swift中数组字典和plist文件的转换
注意:
Swfit
中的Array
和Dictionary
是结构体,是值类型, 没有与plist
相关的接口, 需要先转换为对应的Objectivc-C
类型
1. Array
转为plist
文件(Dictionary类型同理)
// 可能会使用到的接口
1. `Swift`高阶函数`map`(业务代码中的数组元素往往为对象类型, 需要先转换为字典类型, 此处强烈推荐使用高阶函数`map`);
2. `as`转换, 不是`as?`, 也不是`as!`(若原始数据为`Array`类型, 需要先转换为`NSArray`类型, OC的类型才具有相关接口);
3. 沙盒路径获取: NSHomeDirectory();
4. 路径拼接: appendingPathComponent();
5. 写文件: write(toFile:atomically:);
// 实例代码
let targetList: [NSDictionary] = originalList.map {
let dict = NSMutableDictionary()
dict.setValue($0.property0, forKey: "key0")
dict.setValue($0.property1, forKey: "key1")
return dict
}
let array: NSArray = targetList as NSArray
// 获得沙盒的根路径
let home = NSHomeDirectory() as NSString
// 获得Documents路径,使用NSString对象的appendingPathComponent()方法拼接路径
let plistPath = home.appendingPathComponent("Documents") as NSString
// 输出plist文件到指定的路径
array.write(toFile: "\(plistPath)/sqiLocalTarget.plist", atomically: true)
plist
文件转为Array
数据(Dictionary同理)
// 可能用到的接口方法
1. 获取沙盒本地文件路径: Bundle.main.path(forResource:, ofType:)
2. 文件转NSArray: NSArray(contentsOfFile:)
3. 高阶函数: map
if let path = Bundle.main.path(forResource: "sqiLocalTarget", ofType: "plist"), let list = NSArray(contentsOfFile: path) as? [NSDictionary] {
targetList = list.map { (map: NSDictionary) -> 指的的类类型 in
指的的类类型(
property0: map["key0"] as! String,
property1: map["key1"] as! String,
)
}
}