我有一个NSDictionary列表,我想将它保存在一个文件中。我可以将它保存在文本文件中,但我无法将其读取到[NSDictionary]
var text : [NSDictionary] = []
保存文件
let json = JSONSerializer.toJson(text)
try json.write(to: path, atomically: false, encoding: String.Encoding.utf8)
这是我的列表NSDictionary
[{ change = true; name = data1; },{ change = true; name = data2; }]
答案 0 :(得分:0)
do {
let text2 = try NSString(contentsOfURL: path, encoding: NSUTF8StringEncoding) // path give your file path
print(text2)
}
catch {/* error handling here */}
}
试试这个并告诉您的问题是否解决。
答案 1 :(得分:0)
更新代码读取文件
display: flex;
flex-wrap: wrap;
max-width: 1170px;
margin-right: auto;
margin-left: auto;
box-sizing: content-box;
并打印(text2)
let text2 = try String(contentsOf: path!, encoding: String.Encoding.utf8)
print(text2)
arrayFile = try JSONSerializer.toArray(text2) as! [NSDictionary]
print(arrayFile)
答案 2 :(得分:0)
您可以使用plist获取数据字典。以下是我们如何将数据写入plist文件。
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)
要从plist文件中读取数据,
var paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as String
var path = paths.stringByAppendingPathComponent("data.plist")
let save = NSDictionary(contentsOfFile: path)