How do I tell realm that I want it to compute and store read-only property? Let's say I have following model:
class User: Object {
@objc dynamic var fullName: String {
return "\(name) \(surname)"
}
@objc dynamic var name = ""
@objc dynamic var surname = ""
}
I'd like to have formed full name on write action. Is it possible w/o using workaround with dummy setter?
Read-only properties are automatically ignored because it makes absolutely no sense to store them in a database. If you really need to store it in a database, you can create an update function to your User class and use it for saving the entity to database.
Something like this:
class User: Object {
@objc dynamic var fullName = ""
@objc dynamic var name = ""
@objc dynamic var surname = ""
static func create(name: String, surname: String, in realm: Realm) {
let user = realm.create(User.self)
user.name = name
user.surname = surname
user.fullName = "\(name) \(surname)"
}
Then you just create your entity like this:
...
let realm = try! Realm()
try! realm.write {
User.create(name: name, surname: surname, in: realm)
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.