1

I'm using the NSUserDefaults for saving more the 10 big NSDictionarys.

Because the performace is slow, I have the idea to saving the Data into one [or 10 files] instead of using the NSUserDefaults. I need the data just by the starting of the app, so the idea is, saving the data to a file and saving into NSUserDefaults only data I need fast.

I found this solution on stack overflow: Read and write data from text file

let dirs : [String]? = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.AllDomainsMask, true) as? [String]
if ((dirs) != nil) {
    let dir = dirs![0]; //documents directory
    let path = dir.stringByAppendingPathComponent(file);
    let text = "some text"

    //writing
    text.writeToFile(path, atomically: false, encoding: NSUTF8StringEncoding, error: nil);

    //reading
    let text2 = String(contentsOfFile: path, encoding: NSUTF8StringEncoding, error: nil)
}

That works for strings. But when I try to use

NameOfMyDict.writeToFile

I get an error, because Dicts don't have the writeToFile function.

How can I save Dicts to a file?

Community
  • 1
  • 1

2 Answers2

3

NSDictionary provides a function to save to a file. It is part of Foundation framework:

writeToFile(_ path: String, atomically flag: Bool) -> Bool

If you use a swift Dictionary<>, you may need to cast as a NSDictionary. All elements of the dictionary should implement NSCoding protocol.

0

You could serialize it to JSON and save the JSON string to a file. See NSJSONSerialization.

Marcos Crispino
  • 8,018
  • 5
  • 41
  • 59