简体   繁体   中英

Array appending overwrites last index of Realm object

I have an array of Realm objects and before i save them in Realm DB i have my own array of objects in for loop:

var objs = [self.friendsObject] //0 values at first
for i in (0..<json.count) { //counts 2

  let _id = json[i]["_id"] as? String
  let userName = json[i]["userName"] as? String
  let profile_pic = json[i]["profile_pic"] as? String
  let phone = json[i]["phone"] as? String

  self.friendsObject.id = _id!
  self.friendsObject.username = userName!
  self.friendsObject.profilepic = profile_pic!
  self.friendsObject.phone = phone!

  objs.append(self.friendsObject) //2nd element overwrites 1st one
  }
self.friendsObject.save(objects: objs)

So i can see the first object with correct items inside objs before i insert second array, but in second index there are 2 array of objects with same values. i appreciate any help.

Note: It is not duplicate, i have already checked some similar questions but it doesn't apply to my issue.

As Vadian commented, the problem is that the code is not creating new instances of friendsObject but appending the same instance with different values.

Edit

Below an example of how to copy JSON to a class based on the information provided in the question:

    // Simulating a JSON structure filled with some data.
    var jsonData = [Int: [String: String]]()

    for index in 0..<10 {
        var values = [String: String]()
        values["id"] = "id\(index)"
        values["username"] = "username\(index)"
        values["profilepic"] = "profilepic\(index)"
        values["phone"] = "phone\(index)"
        jsonData[index] = values
    }

    // Friend sample class where JSON data will be copied to.
    class Friend {

        var id: String
        var username: String
        var profilepic: String
        var phone: String

        init(_ id: String, _ username: String, _ profilepic: String, _ phone: String) {
            self.id = id
            self.username = username
            self.profilepic = profilepic
            self.phone = phone
        }
    }

    // The array where to copy the values from the JSON data.
    var friends = [Friend]()

    // Looping through the JSON data with a sorted key.
    for jsonSortedKey in jsonData.keys.sorted(by: <) {

        // Obtaining a JSON element containing friend data.
        let jsonFriend = jsonData[jsonSortedKey]!

        // Creating a new friend's instance from the JSON friend's data.
        let friend = Friend((jsonFriend["id"]!), jsonFriend["username"]!, (jsonFriend["profilepic"]!),  (jsonFriend["phone"]!))

        friends.append(friend)
    }

The result is this:

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM