Swift - Read/write array of arrays to/from file

此生再无相见时 提交于 2019-12-05 14:18:11
redent84

Already answered you in your other question:

Here's a full working Playground sample:

let fileUrl = NSURL(fileURLWithPath: "/tmp/foo.plist") // Your path here
let listOfTasks = [["Hi", "Hello", "12:00"], ["Hey there", "What's up?", "3:17"]]

// Save to file
(listOfTasks as NSArray).writeToURL(fileUrl, atomically: true)

// Read from file
let savedArray = NSArray(contentsOfURL: fileUrl) as! [[String]]

print(savedArray)

You should use NSKeyedArchiver/NSKeyedUnarchiver to read/write your array as a property list file instead of a text file. You can save your file to the preferences folder inside the Library folder:

let preferencesDirectory =  try! NSFileManager().URLForDirectory(.LibraryDirectory, inDomain: .UserDomainMask, appropriateForURL: nil, create: true).URLByAppendingPathComponent("Preferences", isDirectory: true)

let listOfTasksURL = preferencesDirectory.URLByAppendingPathComponent("listOfTasks.plist")

var listOfTasks: [[String]] {
    get {
        return NSKeyedUnarchiver.unarchiveObjectWithFile(listOfTasksURL.path!) as? [[String]] ?? []
    }
    set {
        NSKeyedArchiver.archiveRootObject(newValue, toFile: listOfTasksURL.path!)
    }
}

If you would like to test it in a playground file you will need to save it to the documents directory:

let documentsDirectory =  try! NSFileManager().URLForDirectory(.DocumentDirectory, inDomain: .UserDomainMask, appropriateForURL: nil, create: true)

let listOfTasksURL = documentsDirectory.URLByAppendingPathComponent("listOfTasks.plist")

var listOfTasks: [[String]] {
    get {
        return NSKeyedUnarchiver.unarchiveObjectWithFile(listOfTasksURL.path!) as? [[String]] ?? []
    }
    set {
        NSKeyedArchiver.archiveRootObject(newValue, toFile: listOfTasksURL.path!)
    }
}

listOfTasks =  [["Hi", "Hello", "12:00"],["Hey there", "What's up?", "3:17"]]

listOfTasks // [["Hi", "Hello", "12:00"], ["Hey there", "What's up?", "3:17"]]
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!