One-to-one relationship in Realm swift

时间:2018-03-22 14:45:30

标签: ios swift realm

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_id (PK)
  • name
  • age

user_infoA has

  • info_a_id (PK)
  • user_profile

user_infoB has

  • info_b_id (PK)
  • user_profile

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.

1 个答案:

答案 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
   }
}