问题
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