2

I am learning Swift. I have created an dictionary:

var myDict = Dictionary<String, String>()
myDict["AAA"] = "aaa"
myDict["BBB"] = "bbb"

Now I want to persist this dictionary to a file. I get a file path under documents:

let docDir = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).last as? String

let filePath = docDir.stringByAppendingPathComponent("MyFile.txt")

Until here, I don't know how to store myDict to the file. And also how to read the myDict back from file. Could someone please guide me through please?

user842225
  • 5,445
  • 15
  • 69
  • 119

1 Answers1

0

You can use NSMutableDictionary

    private var myDict: NSMutableDictionary!

For writing to user defaults:

    let def:NSUserDefaults = NSUserDefaults.standardUserDefaults();
    def.setObject(myDict, forKey: "YOUR_KEY");
    def.synchronize();

For writing to file:

var text:String = ""
for (key, value) in myDict {
    text += "\(key as! String)=\(value as! String)\n"
}

do {
    try text.writeToFile(path, atomically: false, encoding: NSUTF8StringEncoding)
}
catch {/* error handling here */}

For reading:

    let def:NSUserDefaults = NSUserDefaults.standardUserDefaults();
    let ur:NSDictionary? = def.objectForKey("YOUR_KEY") as? NSDictionary;
    if(ur == nil) {
        myDict = NSMutableDictionary();
        myDict.setValue("aaa", forKey:"AAA");
        myDict.setValue("bbb", forKey:"BBB");
    }
    else{
        myDict = NSMutableDictionary(dictionary: ur!)
    }
Ivan
  • 305
  • 4
  • 9
  • How to create an empty `NSMutableDictionary` in swift? I tried `var myDict : NSMutableDictionary = [String: String]()` But I got error `[String: String] is not convertible to NSMutableDictionary` – user842225 Sep 08 '15 at 12:04
  • Besides, I would like to write the dictionary to a file, I don't want to set to NSUserDefaults – user842225 Sep 08 '15 at 12:08
  • For writing text to file, you can use link [link](http://stackoverflow.com/questions/24097826). Before writing you have to format text with key-value pairs and parse key-value pairs for reading. To create instance use var myDict: NSMutableDictionary = NSMutableDictionary(); – Ivan Sep 08 '15 at 13:15