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)
copy()
function on the object, and inside of it I created a new object, initialized all the fields manually, and then returned it – Agonize