例如,我有两个类:
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条消息,在&#34;更新后#34;因为只有一个用户存在。我该怎么办?
更新 文档中有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."
答案 0 :(得分:3)
这里的问题似乎是,Realm并不知道在此代码块执行之前,同一个用户实际上是与第一个用户相同的用户,因为您在此处将用户添加到Realm:
try! realm.write {
realm.add(theSameUser, update: true)
}
结果就是当你说
时theSameUser.messages.append(message2)
theSameUser.messages
实际上是空的。因此,如果您想要向&#34; user1&#34;添加消息你应该从Realm获取它,然后附加新消息。