[英]Array appending overwrites last index of Realm object
我有一个Realm对象数组,在将它们保存在Realm DB中之前,我在for循环中有自己的对象数组:
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)
因此,在插入第二个数组之前,我可以在objs
看到具有正确项目的第一个对象,但是在第二个索引中,有2个具有相同值的对象数组。 我感谢任何帮助。
注意:它不是重复的,我已经检查了一些类似的问题,但不适用于我的问题。
正如Vadian所评论的那样,问题在于代码不是在创建新的friendsObject
实例,而是将相同的实例附加不同的值。
编辑
下面是一个如何根据问题中提供的信息将JSON复制到类的示例:
// 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)
}
结果是这样的:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.