Reputation: 6009
I have an function to write some numbers to a file
fun writeNumToFile -> Void {
//get Documents’ path
let docPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).last as? String
let filePath = docPath.stringByAppendingPathComponent(“myFlie.txt”)
//the count is NOT the count of elements in the array below.
//think it as an independent constant.
let count = 10
//Write count to file
String(count).writeToFile(filePath, atomically: false, encoding: NSUTF8StringEncoding, error: nil);
//Write an array of numbers to file
for idx in [1,2,3] {
String(idx as! String).writeToFile(filePath, atomically: false, encoding: NSUTF8StringEncoding, error: nil);
}
}
Now I want to read the numbers back from file, I know I can read the content of file by:
let fileContent = String(contentsOfFile: filePath, encoding: NSUTF8StringEncoding, error: nil)
but how can I get count
& [1,2,3]
array back once I get the content?
Upvotes: 1
Views: 58
Reputation: 131511
You are writing code as if you are using low-level file i/o. You're not. The writeToFile:atomically:
methods that you are using overwrite a file with new contents, not append data to an existing file. your second write deletes the contents of your first write.
NSArray
supports the writeToFile:atomically:
method, and a [String]
array should be inter-operable with NSArray.
You should be able to simply say:
let array = [1, 2, 3]
let ok = array .writeToFile(filePath, atomically: false)
Then later,
let array = NSArray.contentsOfFile(filePath)
I say "should be able to" because I am still learning the subtleties of interaction between Swift and the Foundation classes.
If you need to save multiple discrete things into a file, create a dictionary:
let someValue = 42
let anArray = [1, 2, 3]
let aDictionary = [
"someValue": someValue,
"array": anArray]
let ok = aDictionary.writeToFile(filePath, atomically: false)
and to read it:
let aDictionary = NSDictionary(contentsOfFile: filePath)
let someValue = aDictionary["someValue"] as! Int
let anArray = aDictionary["array"] as! [Int]
There is no need to save the number of items in the array separately. The array is able to reconstitute itself from the file contents, including the correct count of elements.
Note that iOS includes the C file i/o library, which should be callable from Swift. If you are glutton for punishment you could do what you are trying to do using fopen()
, fseek()
, fwrite()
, etc. (But don't. It's much more work, much more error-prone, and a non-standard way of doing it in iOS or Mac OS.)
Upvotes: 2