How to get an unmanaged version of a Realm Object
Asked Answered
A

1

7

According to this answer, all that's necessary to get an unmanaged object from an existing managed object is to do this:

let unmanagedObject = Object(value: existingObject)

However, when I do this, any fields of the existingObject that are managed realm objects themselves remain managed realm objects after copying. What do I have to do so that all sub-objects of the copy also become unmanaged?

Agonize answered 8/2, 2017 at 18:24 Comment(2)
hey, were you able to resolve this? I need to do the sameTarrel
@Tarrel Yea, I ended up creating a copy() function on the object, and inside of it I created a new object, initialized all the fields manually, and then returned itAgonize
A
0

The code in the question make an unmanaged copy is correct:

let unmanagedObject = Object(value: existingObject)

But keep in mind that it's a copy of just that object and it's properties - objects referenced by a relationship are not affected nor copied (the reference is copied and can be changed but not the object at that reference)

For example, given a Person and Dog

class Person: Object {
   @Persisted var name = ""
   @Persisted var myDog: Dog!
}

class Dog: Object {
   @Persisted var name = ""
   @Persisted var myPerson: Person!
}

if a person and dog is instantiated

let p = Person()
p.name = "Jay"

let d = Dog()
d.name = "Scraps"

p.myDog = d
d.myPerson = p

then they are written to realm

try! realm.write {
   realm.add(p)
   realm.add(d)
}

Later on we get the person and make an unmanaged copy

let jay = realm.objects(Person.self).where { $0.name == "Jay" }.first!

let jayCopy = Person(value: jay)

jayCopy will have all of the same properties as the original but the reference to the dog will be just that, a reference and not the actual Dog object.

To alter the Dog object, you would also need to make an unmanaged copy of the dog

let dogCopy = Dog(value: jayCopy.dog)
Ator answered 8/4, 2024 at 17:43 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.