How can I model one-to-one relationship between objects?
For example, I have models for user_infoA, user_infoB and user_profile.
user_profile
has
user_infoA
has
user_infoB
has
user_profile
(P) have relationship with both user_infoA
(A) and user_infoB
(B). When A is deleted, also will P be deleted or not? Will P be deleted only if when related A and B are deleted?
And how can I model this with realm swift?
Many-to-one relationship needs optional property, and it makes me use force unwrapping optional. :(
[EDITED]
class RealmMyProfile: Object {
@objc dynamic var id: Int64 = 0
@objc dynamic var profile = RealmUserProfile()
}
class RealmUserProfile: Object {
@objc dynamic var userId: Int64 = 0
@objc dynamic var name: String = ""
override static func primaryKey() -> String? {
return "userId"
}
}
Exception 'The RealmMyProfile.profile
property must be marked as being optional.' occurred. It should be optional.
答案 0 :(得分:1)
Realm中的一对一关系(链接)无法强制始终存在链接。因此,他们总是必须被标记为可选项,因为无法阻止nil以文件格式存储链接。
因此,我们要求Swift中定义的Realm模型明确地将一个关系标记为Optional。
class RealmMyProfile: Object {
@objc dynamic var id: Int64 = 0
@objc dynamic var profile:RealmUserProfile?
}
class RealmUserProfile: Object {
@objc dynamic var userId: Int64 = 0
@objc dynamic var name: String = ""
override static func primaryKey() -> String? {
return "userId"
}
}
您可以使用此解决方案来避免使用展开值
领域问题2814
dynamic var profile_:RealmUserProfile? = nil
var profile: RealmUserProfile {
get {
return profile_ ?? RealmUserProfile()
}
set {
profile_ = newValue
}
}