Paul
Paul

Reputation: 779

One-to-one relationship in Realm swift

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.

Upvotes: 1

Views: 3524

Answers (1)

a.masri
a.masri

Reputation: 2469

To-one relationships (links) in Realm cannot enforce that a link is always present. So they always have to be marked as optional because there's no way to prevent nil from being stored for a link in the file format.

Therefore, we require that Realm models defined in Swift explicitly mark to-one relationships as 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"
  }
}

You can do this solution which may save you from using the unwrapping value

Realm Issue 2814

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

Upvotes: 2

Related Questions