ios - Realm swift 中的一对一关系

标签 ios swift realm

如何为对象之间的一对一关系建模?

例如,我有 user_infoA、user_infoB 和 user_profile 的模型。

user_profile

  • user_id (PK)
  • 姓名
  • 年龄

user_infoA

  • info_a_id (PK)
  • 用户个人资料

user_infoB

  • info_b_id (PK)
  • 用户个人资料

user_profile (P) 与user_infoA (A) 和user_infoB(B) 都有关系。当A被删除时,P是否也被删除?只有删除相关的 A 和 B 时,P 才会被删除吗?

我如何使用 realm swift 对其进行建模?

多对一关系需要可选属性,这让我可以强制展开可选属性。 :(


[编辑]

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"
  }
}

异常“RealmMyProfile.profile 属性必须标记为可选。”发生了。它应该是可选的。

最佳答案

Realm 中的一对一关系(链接)不能强制链接始终存在。所以它们总是必须标记为可选,因为没有办法阻止 nil 被存储为文件格式的链接。

因此,我们要求在 Swift 中定义的 Realm 模型明确地将一对一关系标记为可选。

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"
  }
}

您可以执行此解决方案,这可能会避免您使用解包值

Realm 问题 2814

dynamic var profile_:RealmUserProfile? = nil
var profile: RealmUserProfile {
    get {
        return profile_ ?? RealmUserProfile()
    } 
    set {
        profile_ = newValue
   }
}

关于ios - Realm swift 中的一对一关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49431585/

相关文章:

html - 如何在 iOS 上获取最终的 HTML 字符串

iphone - Objective-C:检查是否使用枚举选项

string - 如何在 Swift 字符串中包含表情符号?

swift - 如何将 ignoredProperties 与多个变量一起使用?

iOS 动画 clipToBounds、masksToBounds 或类似的

ios - Xcode 静态 UITableView 单元格在 Storyboard中为空白

ios - IDEBundleInjection.c : Error 3587 on Xcode 6. 4

ios - 通过 NSDate 检查值是否存在作为字典中的键

swift - 在设备上运行时无法连接到 Realm 对象服务器

android - 带新国外 Realm 的 Realm 迁移