我有一个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个具有相同值的对象数组。我感谢任何帮助。
注意:这不重复,我已经检查了一些类似的问题,但它并不适用于我的问题。
答案 0 :(得分: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)
}
结果如下: