问题
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