swift - Realm 正在重写而不是更新嵌套的对象数组

标签 swift realm

例如,我有两个类:

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/

相关文章:

ios - 是否有类似分页的代码用于将 JSON 数据保存到 Realmdatabase

ios - 反向关系过滤列表

ios - 导航栏 removeGestureRecognizer 没有删除 Gesture

swift - 快速调用 NSMutableData 上的 map

ios - 如何在 Realm 中存储 NSObject 类?

ios - 排除 Realm 模型类

ios - Swift 中 Realm 查询的交叉引用谓词

swift - 带字符串的 swift 类字典

swift - 当从 xib 加载 subview 到 UIScrollView 时,快速出现错误 'EXC_BAD_ACCESS'

ios - 如何在swiftui中使用内部选择器中的切换以及如何基于切换来更改选择器值