例如,我有两个类:
class Message : Object {
dynamic var text_ : String = ""
convenience init(text: String) {
self.init()
text_ = text
}
override static func primaryKey() -> String? {
return "text_"
}
}
class UserProfile : Object {
dynamic var username_ : String = ""
var messages = List<Message>()
convenience init(username: String) {
self.init()
username_ = username
}
override static func primaryKey() -> String? {
return "username_"
}
}
所以我得到了用户,以及他所有消息的列表,我希望能够在我从某处获得新的 UserProfile 实例时更新该列表:
let realm = try! Realm()
let user1 = UserProfile(username: "user1")
let message1 = Message(text: "message1")
user1.messages.append(message1)
try! realm.write {
realm.add(user1, update: true)
}
let results1 = realm.objects(UserProfile)
print("Before updating: \(results1[0].messages)")
let theSameUser = UserProfile(username: "user1")
let message2 = Message(text: "message2")
theSameUser.messages.append(message2)
try! realm.write {
realm.add(theSameUser, update: true)
}
let results2 = realm.objects(UserProfile)
print("After updating: \(results2[0].messages)")
输出是:
Before updating: List<Message> (
[0] Message {
text_ = message1;
}
)
After updating: List<Message> (
[0] Message {
text_ = message2;
}
)
但它应该在“更新后”中同时包含 2 条消息,因为只存在一个用户。我该怎么办?
更新: 文档中有 Realm 示例。与我的示例唯一不同的是 Realm 对象列表:
// Creating a book with the same primary key as a previously saved book
let cheeseBook = Book()
cheeseBook.title = "Cheese recipes"
cheeseBook.price = 9000
cheeseBook.id = 1
// Updating book with id = 1
try! realm.write {
realm.add(cheeseBook, update: true)
}
If a Book object with a primary key value of ‘1’ already existed in the database, then that object would simply be updated. If it did not exist, then a completely new Book object would be created and added to the database."
最佳答案
这里的问题似乎是 Realm 不知道 theSameUser 实际上是执行此代码块之前的第一个用户,因为您在此处将用户添加到 Realm:
try! realm.write {
realm.add(theSameUser, update: true)
}
结果就是当你说
theSameUser.messages.append(message2)
theSameUser.messages
实际上是空的。因此,如果您想将一条消息附加到“user1”,您应该从 Realm 中获取它,然后附加新消息。
关于swift - Realm 正在重写而不是更新嵌套的对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36086063/