運行函數testThis()來查看這一切。 self.user.jsonTest是Transformable類型的核心數據變量。將其替換爲任何可變形的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()
}
請張貼相關的代碼 – 2013-02-13 05:42:52
'results_category_list = [NSJSONSerialization JSONObjectWithData:數據選擇:NSJSONReadingMutableLeaves誤差:&myError];' – 2013-02-13 05:47:59
爲什麼不把它保存爲數據?在覈心數據模型中將類型更改爲blob,保存從URL返回的數據並在需要時將其轉換爲字典表示形式? – bennythemink 2013-02-13 05:48:57