ios - Working with Realm and result JSON -
i new realm , trying use realm in project. here trying parse json , save using realm. when trying loop through result array error occurs
'attempting modify object outside of write transaction - call beginwritetransaction on rlmrealm instance first'
this json result:
{"data":[{"id":1,"parent_id":0,"name":"jennifermaenle","title":"ms","phone":"","address":"toled, ohio","email":"jlmaenle@aol.com","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"}]}
i trying parse json , save in realm database. here try:
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() { if let json = try jsonserialization.jsonobject(with: data) as? [string: anyobject] { if let data = json["data"] as? [[string:anyobject]]{ 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)") } }
do not modify persons
object , add realm again. error see because add persons realm , edit on second iteration in for eachitem in data
again. persons
added realm in iteration , try give new name outside realm write transaction. that's why see error. it's better create new object every person.
func add(){ guard let data = datafromfile("serverdata") else { return } { if let json = try jsonserialization.jsonobject(with: data) as? [string: anyobject] { if let data = json["data"] as? [[string:anyobject]]{ 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)") } }
Comments
Post a Comment