如何将数组写入plist?

时间:2016-05-11 14:44:19

标签: ios swift nsarray plist

我想在.plist中写一个数组,但在调用该函数后,没有任何内容在.plist中。

这是我的代码:

override func viewDidLoad() {
        super.viewDidLoad()
        var filepath = NSHomeDirectory().stringByAppendingString("/lacator.plist")
        let array:NSArray = ["b","a","n","d"]
        array.writeToFile(filepath, atomically: true)

}

放置了文件:

/var/mobile/Containers/Data/Application/AE38143E-C398-4DA7-952D-4E1C903E9637/locator.plist

但我找不到文件夹......

3 个答案:

答案 0 :(得分:2)

正如@dan所提到的,你不能写到主目录,考虑写入文件夹:

    func applicationDocumentsDirectory() -> String {
        let paths = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)
        let basePath = paths.first ?? ""
        return basePath
    }

    let filepath = applicationDocumentsDirectory().stringByAppendingString("/lacator.plist")
    let array:NSArray = ["b","a","n","d"]
    array.writeToFile(filepath, atomically: true)

    print("Does file exist: \(NSFileManager.defaultManager().fileExistsAtPath(filepath)) at path: \(filepath)")

输出

    Does file exist: true at path: /var/mobile/Applications/2754A65C-DF1B-4B69-9FC5-A3A171D88087/Documents/lacator.plist

如果您从iTunes启用了文档文件夹访问权限,则可以从iTunes获取此文件:

iTunes Documents Directory in my app

答案 1 :(得分:0)

与@lgor B.的答案相同,但具有 swift 5

struct JSONManager {

    private static var applicationDocumentsDirectory: String? {
        let paths = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)
        return paths.first
    }

    private static var mockDataPath: String? {
        guard let basePath = JSONManager.applicationDocumentsDirectory else {
            return .none
        }
        return basePath.appendingFormat("/yourPlistName.plist")
    }

    static func save(_ array: NSArray) {

        guard let path = mockDataPath else { return }
        array.write(toFile: path, atomically: true)

        assert(FileManager.default.fileExists(atPath: path))
    }

}

如果您还想阅读它,请将这两种方法添加到JSONManager中:

    static func readArray() -> NSArray? {
        guard let path = mockDataPath else { return .none }
        return NSArray(contentsOfFile: path)
    }

    static func readDicionary() -> NSDictionary? {
        guard let path = mockDataPath else { return .none }
        return NSDictionary(contentsOfFile: path)
    }

答案 2 :(得分:0)

现在(2019年,但实际上是自2016年Swift 3发行以来),强烈建议使用PropertyListSerializationFilemanager的URL相关API。

首先创建一个计算变量,该变量将当前URL返回到文档目录

var documentsDirectoryURL : URL {
    return try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false)
}

强制展开的URL很安全,因为可以确保存在文档目录。


使用PropertyListSerialization序列化数组并将数据写入URL

let fileURL = documentsDirectoryURL.appendingPathComponent("lacator.plist")
let array = ["b","a","n","d"]
do {
    let data = try PropertyListSerialization.data(fromPropertyList: array, format: .binary, options: 0)
    try data.write(to: fileURL)
} catch {
    print(error)
}

如果类型符合PropertyListEncoder,则在带有Encodable的Swift 4+中更方便

do {
    let data = try PropertyListEncoder().encode(array)
...