运行函数 testThis() 来查看这一切。self.user.jsonTest 是一个可转换类型的核心数据变量。将其替换为任何可转换的 CoreData 变量,并且 storeJSON 和检索 JSON 应该可以工作。我正在使用 swiftyJSON,但如果你不使用它应该非常容易删除它。
func testThis() {
makeFakeData() {
self.retrieveJSON(self.user.jsonTest) {
json in
print("json: \(json)")
}
}
}
func storeJSON(dataToStore: [String: AnyObject], completion: (data: NSData?) -> Void) {
do {
let data = try NSJSONSerialization.dataWithJSONObject(dataToStore, options: [])
completion(data: data)
} catch let error as NSError {
print("NSJSONSerialization Error: \(error)")
completion(data: nil)
}
}
func retrieveJSON(dataToGet: NSObject?, completion: (json: JSON?) -> Void) {
if let data = dataToGet as? NSData {
do {
let nsJSON = try NSJSONSerialization.JSONObjectWithData(data, options: [])
completion(json: JSON(nsJSON))
} catch let error as NSError {
print("NSJSONSerialization Error: \(error)")
completion(json: nil)
}
}
}
func makeFakeData(completion: () -> Void) {
var solarResourceDic: [String: String] = [:]
var srDics: [[String: String]!] = []
for i in 0..<5 {
solarResourceDic = [:]
solarResourceDic["system_capacity"] = "\(i)"
solarResourceDic["azimuth"] = "\(i + 1)"
solarResourceDic["tilt"] = "\(i + 2)"
solarResourceDic["array_type"] = "\(i + 3)"
solarResourceDic["module_type"] = "\(i + 4)"
solarResourceDic["losses"] = "\(i + 5)"
srDics.append(solarResourceDic)
}
let dic = ["Solar Resource": srDics]
storeJSON(dic) {
data in
self.user.jsonTest = data
appDelegate.coreData.saveContext()
}
completion()
}