Array appending overwrites last index

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 = _id!
  self.friendsObject.username = userName!
  self.friendsObject.profilepic = profile_pic! = phone!

  objs.append(self.friendsObject) //2nd element overwrites 1st one
  } 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.

1 answer

  • answered 2017-06-17 19:30 Jack G.

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