Realm Sync + SwiftUI: Object is already managed by another Realm. Use create instead to copy it into this Realm

Thanks Diana,

That solution only works for an on device Realm right? I am trying to use a synced realm.

I’ve tried accessing the realm via @Environment(\.realm) var realm: Realm but all my queries are returning zero results.

I am injecting the realm into the environment via the standard process:

        HouseholdsView()
            .environment(\.realm, realm) // Where realm is coming from autoOpen

I’ve also tried this:

func onInsertItem(name: String, listId: String) {
        guard let realm = list.realm?.thaw() else {
            return
        }

        guard let list = realm.object(ofType: List.self, forPrimaryKey: listId) else {
            print("No list found with PK \(listId)")
            return
        }

        let listItem = ListItem()
        let arrayItem = realm.objects(Household.self).compactMap { $0.itemTypes }.flatMap { $0 }
        if let itemType = arrayItem.first(where: { $0.name == name }) {
            listItem.itemType = itemType
        } else {
            // item type does not exist
            let itemType = ItemType();
            itemType.name = name
            listItem.itemType = itemType
        }

        try! realm.write {
            list.listItems.append(listItem)
        }
    }

and it almost works. I can insert as many items as I want into my list, but it always falls into the “item type does not exist branch”. I’m assuming this is because the Realm I’m using is attached to the list object, so it doesn’t contain the itemTypes which are in a different instance of Realm?

I’m experiencing this issue as well.

The guide here says to append a new item to the Observed results like:

$groups.append(Group())

The issue seems to be that if you want to initiate any values, there isn’t a functioning way to do that ( or at least the documentation / example is not complete).

I’ve tried to pass in params for initiation like:

$groups.append(Group(name: "Group Name"))

but that is not possible.

Alternatively I have tried to initiate the object first, set the initial parameters and then append, but that gives the error @Campbell_Bartlett has described here.

It’s as if initiating the object is automatically assigning it to some local Realm even when using a synced Realm, so then it can’t append it as demonstrated in the example.

Even if I pass in the correct environment in SwiftUI to the view with a ..environment(\.realmConfiguration, app.currentUser!.configuration(partitionValue: "user=\(app.currentUser!.id)")) and establish the correct default _partition in the Realm Model, it is still creating the object in some other Realm and throwing the error.

I know there has got to be a best practice for creating new objects in SwiftUI that allows for initial parameters to be passed in, it is just very unclear how to do this.

1 Like

@Kurt_Libby1 I cannot reproduce your issue. Passing params to a constructor on an object should not involve a Realm unless there is one involved inside the constructor. Could you open a GitHub issue showing your usage?

Hey Lee.

I’m probably saying it wrong if you think it shouldn’t involve a Realm.

I’m talking about setting properties for a Realm object and then adding it in the prescribed way.

Your example is about adding a Group Realm object by appending Group() with the @ObservedResults property wrapper and the using .append()

Your example is extremely basic. For anything more complex, there is no example and that was my comment – either the example is incomplete or there isn’t a good way to do this.

In my app I am checking to see if there is a plan with a location like this:

@ObservedResults(Plan.self) var plans
@StateRealmObject var location: Location
...
if let plan = plans.filter("location._id = %@", location._id).first {
  // show plan
} else {
  // add location to plan like this:
  $plans.append(Plan(_id: UUID(), _partition: "user=\(app.currentUser!.id)",location: self.location))

  // because if I do it as prescribed like this:
  $plans.append(Plan())
  // it works, but there is no way to add the location, so there's just an empty Plan object added to the database
}

This doesn’t work.

I’ve tried to pass in the location as a var, as @ObservedRealmObject, and as @StateRealmObject as shown above. No matter what it always shows the error:

Object is already managed by another Realm. Use create…

I’m not super interested in opening a GitHub issue. I’m more interested in documentation and/or examples that goes beyond the most basic usage. Again, surely there is a way to do this, but either I’m misunderstanding how to do this in Realm, or I’m not saying it correctly. Either are entirely possible.

1 Like

@Kurt_Libby1 I see what you mean, this is for sure something we can improve on. My first idea to resolve the issue would be to use the Realm.create(_, value:, update:) API. The usage would be like so:

let realm = plans.thaw()!.realm!
try! realm.write {
    $plans.append(realm.create(Plan.self, value: Plan(_id: UUID(), _partition: "user=\(app.currentUser!.id)",location: self.location), update: .modified)
}

1 Like

I solved my issue by adding the plan to the location when the location was created.

( I would love to know where in the documentation your approach is presented because I’ve never seen this update: .modified before. )

Also, I’m again running into the same error today in another view where I’m loading a bunch of tags and trying to add them to a list of tags on another object.

Simple example is like this:

@ObservedResults(Tag.self) var tags
@ObservedRealmObject var room: Room

// Room() has a property defined as @Persisted var tags = RealmSwift.List<Tag>()

ForEach(tags) { tag in
  Text(tag.name)
    .onTapGesture {
      $room.tags.append(tag)             
    }
}

I’m getting this same error:

Object is already managed by another realm.

What I don’t understand is this:

I only want to use one realm. It’s synced. It’s a partition set with the logged in user’s id as user=\(app.currentUser!.id). And every interaction with realm should be with this realm. Every part of my object model has this _partition set in the definition of the model.

So why are there other realms? How can I make it so that there are no other realms and every CRUD is always on this one realm with this one partition?

And again, I can’t find any documentation that helps explain this in a clear enough way. For the sake of presenting realm as simple, it seems like anything beyond the examples just break the functionality.

I know this probably isn’t the case, but that is how it seems.

Any insight and links to additional documentation would be super helpful.

Thanks.

1 Like

Hi,

I think the issue you are having is caused by @ObservedResults(Tag.self) var tags realm instance being different from @ObservedRealmObject var room: Room realm. I had the same problem and something like this worked from me:

ForEach(tags) { tag in
  Text(tag.name)
    .onTapGesture {
      $room.tags.append(room.realm.objects(Tag.self).first(where: {$0._id == tag._id})             
    }
}

I hope this will help you.

Best regards,
Horatiu

Thanks Hortiu,

But that didn’t work.

I had to add some bangs for the optionals, but I got the same “Object is already managed by another Realm” error.

Here is the code with the bangs to make the complier happy:

$room.tags.append(room.realm!.objects(Tag.self).first(where: {$0._id == tag._id})!)

So this doesn’t work, AND it still doesn’t explain my main questions.

Why is there another realm? How can I make sure that there is only ever one realm?

I want my users to log in and always have the same realm. Always.

I have other apps where I go back and forth between multiple realm partitions, and I though this implementation would be easy, but it is definitely not.

Does your Tag type has other realm properties? Realm raises the same exception when you append a tag object that has other realm objects as its properties. It also sees those nested objects coming from a different realm.

Regarding the different realms, I don’t know why. I faced the same problems and I noticed that, in my case, realm instances were different.

About the realm query, you could let swift do the unwrapping:

$room.tags.append(room.realm?.objects(Tag.self).first(where: {$0._id == tag._id}) ?? tag)

Horatiu

My Tag type did have other Realm properties. So this morning I restructured the app so that it doesn’t, but that didn’t solve my issue. Still got the same Object is already managed by another Realm error.

Spent a couple of hours trying different things and stripping it down to a basic app that you can find here.

Ultimately I discovered that the object with the list as well as the object being added to the list both have to be thawed before it works:

  let thawedRoom = room.thaw()!
  let realm = thawedRoom.realm!
  let thawedTag = tag.thaw()!
                  
  do {
    try! realm.write {
      thawedRoom.tags.append(thawedTag)
    }
  }

Hopefully the Realm team can figure out a way for this to be clearer and for the implicit writes to work beyond extremely basic examples. And then also add to the documentation how to get this to work with only one Realm so we can stop running into these “another Realm” errors when 99% of the time we only ever want to deal with one Realm.

1 Like

I agree with @Kurt_Libby1

It is a bit frustrating this confusion about “managed by another realm”.

The default behavior must be a “single realm”. I don’t want another Realm. Please “Mr. realm swift” , just use the single existing Realm.

“let realm = try! Realm()”

Why should I care about “another realms” if I just declared a single realm instance ?

Can someone from mongo staff give some guidance ?

2 Likes

@Robson_Tenorio

Do you have a specific use case? This:

let realm = try! Realm()

Doesn’t create “another realm” it accesses the same Realm that everything else on that thread accesses. If you’re on a different thread however, say a background thread, then it would (could) be “another realm”.

This is especially try if you’re using sync’ing and are writing on the UI thread as Sync writes on a background thread so there would be “another realm” in that case.

Got some a troublesome code example you can post?

While Robson may have some troublesome code to post, I will say that the continued frustration with using any synced Realm is just how hard it is to do exactly what the complaint/agreement is here.

Rather than posting “troublesome code”, it would be infinitely more beneficial for MDB to provide code examples of how to easily create one synced realm and always use that.

The back and forth on every screen in every way that I handle writing and reading from Realm seems to behave in completely unpredictible ways as I’m constantly thawing or needing to find clever places to add writes just to “make sure” the object isn’t managed by another Realm.

As I shared before and was not provided an answer, I will share again:

I want my users to log in and always have the same realm. Always.

There is no clean example of this that I know of in the documentation, nor as a response to my earlier post six months ago. Rather than seeing an answer to my or Robson’s troublesome code, I would sincerely love a straightforward answer about how the above quoted line should be achieved.

As SJ would have said, maybe we’re just “holding it wrong.”

That’s fine. I’ll admit to that. I just want to be shown how to hold it.

2 Likes

@Kurt_Libby1

I think you missed my point, or perhaps it was too vague. The post referenced “a single realm” and the code presented

“let realm = try! Realm()”

does exactly that - a single realm. If you call that 900000 times in your app, you’re still going to have “a single realm”

When there isn’t a “single realm” is when a Realm is instantiated on different threads, say in the UI thread and then again in a background thread - and then objects are addressed from those “different realms”. I provided an example of that in my response above.

My query was in an effort to assist - requesting a short verifiable example to see what that user is experiencing to try to match it up with your initial code is not unreasonable.

If you review the TaskTracker Sync sample app, you’ll find that when a users logs in they always have the same Realm. Always.

The goal is to identify why your code behaves differently and IMO more data is needed.

1 Like

So the issue here is when we append an object with a nested managed object, for example for the following model from the initial post.

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 Object is already managed by another Realm. Use create instead to copy it into this Realm. 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 reason for this, is that when the write is done, we only check if TopLevel object has a realm associated but because in this case it doesn’t (is unmanaged) we don’t thaw it to use the same realm as the write, we don’t check any nested if any nested properties has a managed object.
For this to work, 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.

There is a workaround for this, you can use create, like the following code.

let realm = list.thaw()!.realm!
try! realm.write {
   let listItem = realm.create(ListItem.self, value: ["itemType": itemType], update: .modified)
   $list.listItems.append(listItem)
}

This is something we clearly have been taking a look, and I just opened a GitHub issue to track any progress SwiftUI Property Wrappers Improvement · Issue #7942 · realm/realm-swift · GitHub on this.

1 Like

Thanks Diana.

This is how I do it as well. I have that thaw workaround all over my apps to account for this bug. I’ll watch the issue you shared for sure. I think the frustrating thing here is what you pointed out at the beginning of your post and still is the spirit of this discussion:

Once a user logs in, 99% of the time we only ever want to use their realm. So instead of creating “unmanaged” objects, I would love it if every newly created object was managed by that user’s realm unless explicitly stated otherwise. We’re adding the same bit of code all over the app for all different kinds of writes and it’s exactly the clunky boilerplate that is antithesis to the spirit of Realm.

Very pleased to know that this is being addressed and will be resolved soon. --Kurt

PS: I do have one app where I switch the Realm environments by passing it in the .environment() and I have always assumed that passing the Realm in the environment will make any objects created in that View managed by that Realm, but it does not seem to be the case. This has added to the confusion as well.

Hey Diana,

Thank you for getting back to me, I am glad the team is looking to simplify things so others don’t run into the same problem.

I appreciate that you have taken the time to update me about such an old issue!

Is this specifically an issue in SwiftUI only?

It seems to work in Swift without that error message (if I am duplicating the issue correctly, which is questionable lol)

The best way to exemplify this will be with the following code snippet

let config = Realm.Configuration.defaultConfiguration
let realm = try! Realm(configuration: config)
let list = List()
list.name = "list_\(Int.random(in: 0...100))"
try! realm.write {
   realm.add(list)
}
let frozenList = list.freeze()
try! realm.write {
   let household = Household()
   realm.add(household)
   household.name = "name_\(Int.random(in: 0...100))"
   household.lists.append(frozenList)
}

Even though list belongs to the same realm we are using to write household, when we append a frozen instance of list it throws the same error (Object is already managed by another Realm. Use create instead to copy it into this Realm.).
In our SwiftUI implementation, we try to avoid this by thawing the object before appending it to the list, but because in this case there is a nested object within the newly created object, we are not doing. Like in my previous post, the solution will be to do a recursive check for sub-objects when users try to append an object.

1 Like

@Diana_Maria_Perez_Af

Just a question and a comment in our use case - and maybe I misunderstand, but that example doesn’t appear to agree with the documentation;

which states

You must thaw both the object you want to append and the collection you want to append it to.

so this does not work (and shouldn’t because frozen objects cannot be modified, and appending is modifying)

household.lists.append(frozenList)

but you said

For clarification, are the SwiftUI wrappers (attempting to) unfreezing these objects while it’s a manual thing in Swift?

To me it all comes down to the phrasing of the error message Object is already managed by another Realm

A frozen object isn’t really a “managed object”; it can’t be modified, written or really have anything done with it other than passing it around and looking at it.

Why should I care about “another realms” if I just declared a single realm instance ?

If it’s thawed you get back the Realm is was spawned on, which would be the “single realm instance”.

If we’re adhering to the docs the code should be

try! realm.write {
   let household = Household()
   realm.add(household)
   household.name = "name_\(Int.random(in: 0...100))"
      let thawedList = frozenList.thaw() //this is "the same Realm" and "only one realm"
   household.lists.append(thawedList)
}

Frozen objects remain valid as long as the live realm that spawned them stays open

So this sounds like an issue specific to SwiftUI - in Swift, as long as we thaw object before writing etc, then we only ever have a “single realm instance” and don’t encounter that error message.