2017-08-15 86 views
3

我是新來的領域,我想在我的項目中使用領域。在這裏,我試圖解析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)") 
    } 
} 

回答

2

不要修改persons對象並再次將其添加到領域。您看到的錯誤是因爲您將人員添加到領域,然後再次在for eachItem in data的第二次迭代中對其進行編輯。在本次迭代中,Persons已被添加到領域,並且您嘗試在領域寫入事務之外爲其指定一個新名稱。這就是你看到錯誤的原因。爲每個人創建一個新對象會更好。

func add(){ 
    guard let data = dataFromFile("ServerData") else { return } 

    do { 
     if let json = try JSONSerialization.jsonObject(with: data) as? [String: AnyObject] { 
      if let data = json["data"] as? [[String:AnyObject]]{ 
       for eachItem in data{ 
        let persons = Person() 
        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)") 
    } 
} 
+1

謝謝@Yannick工作完美:) –

2

由於錯誤表示,需要大跳寫內部的事務,

一種選擇是單獨寫每個人:

for eachItem in data{ 
    let person = Person() 
    person.name = eachItem["name"] as! String 
    person.title = eachItem["title"] as! String 
    person.address = eachItem["address"] as! String 

    try! realm.write { 
     realm.add(person) 
    } 
} 

第二個選項是建立一個對象,然後寫入:

for eachItem in data{ 
    let person = Person(); 
    person.name = eachItem["name"] as! String 
    person.title = eachItem["title"] as! String 
    person.address = eachItem["address"] as! String 
    persons.add(person) 
} 
try! realm.write { 
    realm. append(persons) 
} 

您可能需要對此進行少許更改,但這是主意。