我是新來的領域,我想在我的項目中使用領域。在這裏,我試圖解析JSON並使用領域進行保存。當我在結果陣列錯誤試圖環路發生使用領域和結果JSON
「試圖修改寫入事務之外的物體 - 先請一個RLMRealm實例beginwritetransaction」
這是JSON結果:
{"data":[{"id":1,"parent_id":0,"name":"JenniferMaenle","title":"Ms","phone":"","address":"Toled, ohio","email":"[email protected]","image":"44381525_2017.jpg","relation_id":5,"created_at":null,"updated_at":"2017-08-10 02:30:05"},{"id":2, "parent_id":1,"name":"Khadeeja","title":"","phone":"","address":"","email":"","image":"Khadeeja_2017-07-17.jpg","relation_id":2,"created_at":null,"updated_at":"2017-07-17 08:3:12"}]}
我想解析JSON並將其保存在Realm數據庫中。這裏是我的嘗試:
class Person: Object {
dynamic var name = ""
dynamic var title = ""
dynamic var address = ""
}
override func viewDidLoad() {
super.viewDidLoad()
self.add()
}
func add(){
guard let data = dataFromFile("ServerData") else { return }
let persons = Person()
do {
if let json = try JSONSerialization.jsonObject(with: data) as? [String: AnyObject] {
if let data = json["data"] as? [[String:AnyObject]]{
for eachItem in data{
persons.name = eachItem["name"] as! String
persons.title = eachItem["title"] as! String
persons.address = eachItem["address"] as! String
try! realm.write {
realm.add(persons)
}
}
}
}
} catch {
print("Error deserializing JSON: \(error)")
}
}
謝謝@Yannick工作完美:) –