0

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 ?

user842225
  • 5,445
  • 15
  • 69
  • 119

1 Answers1

0

You are on the right track

For a simple data type, using the DocumentDirectory the way you have is very nice. It simple to implement, and is easy to access values from. Using that method doesn't mean you have to save a .txt file though. Have you considered saving as a plist file? That will allow you keep the entry as a Bool, Number, Date or String - eliminating conversion. For more information on saving plist to NSUserDefaults, click here Save Data to .plist File in Swift

Plists are great, but have limitations

You can save lots of other types in a plist as well, but you need to encode them as an NSData object to be saved in a plist. This can be dangerous, though. It is so easy to use plists for storage that it tempts us to abuse them. Plists aren't meant to be a database, and they can cause your app to be very slow and memory inefficient if you rely on them for storing things like images or arrays of images(yikes).

For more intense storage look at CoreData

If you end up wanting to save things like images or enormous amounts of data, you will need to investigate something like Core Data, which is essentially a data model (kind of a database) that your app can run with. If you end up needing this, save yourself a headache and look into the MagicalRecord github (https://github.com/magicalpanda/MagicalRecord).

Community
  • 1
  • 1
Charlie
  • 1,279
  • 2
  • 12
  • 28