Swift - Unable to read/write from file

淺唱寂寞╮ 提交于 2019-12-13 02:40:01

问题


I'm actually not sure whether I'm not able to read or unable to write. I'm pretty sure writing works. I'm using Swift.

Here are my project files.

I'm trying to write an array of arrays to a file, and then read that array of arrays when the app launches. Here's my code for writing and reading, respectively. listOfTasks is my array of arrays variable.

Writing:

let cocoaArray : NSArray = listOfTasks
cocoaArray.writeToFile(String(fileURL), atomically: true)

Reading:

listOfTasks = NSArray(contentsOfFile: String(fileURL)) as! [Array<String>]

fileURL:

let documentsDirectory = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).last

let fileURL = documentsDirectory!.URLByAppendingPathComponent("file.txt")

I'm happy to provide additional information as necessary. Thanks in advance!


回答1:


Not sure where's exactly your problem, but here's a full working Playground sample:

let fileUrl = NSURL(fileURLWithPath: "/tmp/foo.plist") // Your path here
let array = [["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"], ["One", "Two", "Three"]] // Your array of arrays here

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

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

print(savedArray)


来源:https://stackoverflow.com/questions/37582591/swift-unable-to-read-write-from-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!