Write and read file with list NSDictonary swift

吃可爱长大的小学妹 提交于 2019-12-12 05:14:12

问题


I have a list of NSDictionary, and i want to save it in a file. I can save it in text file but i can't read it to [NSDictionary]

var text : [NSDictionary] = []

save file

let json = JSONSerializer.toJson(text)
try json.write(to: path, atomically: false, encoding: String.Encoding.utf8)

This is my list NSDictionary

[{ change = true; name = data1; },{ change = true; name = data2; }]

回答1:


do {
        let text2 = try NSString(contentsOfURL: path, encoding: NSUTF8StringEncoding) // path give your file path
        print(text2)
    }
    catch {/* error handling here */}
}

Try this and tell is your problem solve or not .




回答2:


update code read file

let text2 = try String(contentsOf: path!, encoding: String.Encoding.utf8)
                    print(text2)
                    arrayFile = try JSONSerializer.toArray(text2) as! [NSDictionary]
                    print(arrayFile)

and print(text2)

{[{ 
change = true;
name = data1;
},{
change = true;
name = data2;
}]}



回答3:


You can user plist for dictionary of data. Here is how we write data to plist file.

var paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as String
var path = paths.stringByAppendingPathComponent("data.plist")
var fileManager = NSFileManager.defaultManager()
if (!(fileManager.fileExistsAtPath(path)))
{
    var bundle : NSString = NSBundle.mainBundle().pathForResource("data", ofType: "plist")
    fileManager.copyItemAtPath(bundle, toPath: path, error:nil)
}
data.setObject(object, forKey: "object")
data.writeToFile(path, atomically: true)

To read data from plist file,

var paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as String
var path = paths.stringByAppendingPathComponent("data.plist")
let save = NSDictionary(contentsOfFile: path)


来源:https://stackoverflow.com/questions/40316086/write-and-read-file-with-list-nsdictonary-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!