I want to write data to a file, if file is not exist, create it otherwise overwrite it. I am using Swift. This is what I tried while learning Swift:
//Get documents directory
let docDir = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).last as? String
//get file path, I write data to this file
let filePath = docDir!.stringByAppendingPathComponent(“myFile.txt”)
//Write integer data to file
let intData = 10
String(intData).writeToFile(filePath, atomically: false, encoding: NSUTF8StringEncoding, error: nil);
//Write String data to file
let strData = “strstr”
strData.writeToFile(filePath, atomically: false, encoding: NSUTF8StringEncoding, error: nil);
Since I am newbie in iOS & Swift, I am wondering is there a better way to do things?
(At least, I feel that in my current code, I need to always convert integer to String before writing to file which is verbose.)
===Update===
I googled & found someone uses NSOutputStream
to achieve the similar thing, I am wondering which is better & why, when is better to use NSOutputStream
?