realm / realm-swift

Realm is a mobile database: a replacement for Core Data & SQLite
https://realm.io
Apache License 2.0
16.27k stars 2.14k forks source link

SwiftUI Property Wrappers Improvement #7942

Open sync-by-unito[bot] opened 2 years ago

sync-by-unito[bot] commented 2 years ago

Been able to append an unmanaged objects with a nested managed object. At the moment trying to append an unmanaged object with a nested managed object is crashing with the following error Object is already managed by another Realm. Use create instead to copy it into this Realm.

Reproduction: For the following object model

final class ListItem: Object, ObjectKeyIdentifiable {
  @Persisted var _id: String = UUID().uuidString
  @Persisted var itemType: ItemType?
  @Persisted var quantity: String?
  @Persisted var note: String?
}

we get an error for the following operation

let listItem = ListItem() // Create unmanaged object
listItem.itemType = itemType // We are setting a managed object to a property of an unmanaged object
$list.listItems.append(listItem) // We append the unmanaged object

The issue happens because we only check that the TopLevel object has a realm when we do the write, and only if that's the case we thaw it to use the same realm. We would have to verify not only if the TopLevel Object has an associated realm, but if any set property has it, and make sure they use the same realm. In conclusion, we will have to do a recursive check for sub-objects when users try to add an unmanaged object.

Associated forum post: https://www.mongodb.com/community/forums/t/realm-sync-swiftui-object-is-already-managed-by-another-realm-use-create-instead-to-copy-it-into-this-realm/148123

NOTE: We should throw a better error message in cases of trying to do a write with a frozen object.

Gregliest commented 1 year ago

Has there been any movement on this? It seems like this is a pretty basic use case with a misleading error message, and I had to dig pretty deep to find this issue as the root cause.

craigjarman commented 3 months ago

Still seems to be an issue

misterlib commented 4 weeks ago

Closing in on a full 2 years. Still an issue 😬

misterlib commented 3 days ago

oof. that's why. 🥺

aehlke commented 2 days ago

@misterlib that's why..? I see the v20 release but that's not a 2 year effort

edit: ah I see the deprecation notice now. hmmm