Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I easily duplicate/copy an existing realm object

Tags:

swift

realm

I have a Realm Object which has several relationships, anyone has a good code snippet that generalizes a copy method, to create a duplicate in the database.

like image 743
mvo Avatar asked May 09 '15 20:05

mvo


3 Answers

In my case i just wanted to create an object and not persist it. so segiddins's solution didn't work for me.

Swift 3

To create a clone of user object in swift just use

let newUser = User(value: oldUser);

The new user object is not persisted.

like image 57
Cerlin Avatar answered Nov 10 '22 20:11

Cerlin


You can use the following to create a shallow copy of your object, as long as it does not have a primary key:

realm.create(ObjectType.self, withValue: existingObject)
like image 7
segiddins Avatar answered Nov 10 '22 20:11

segiddins


As of now, Dec 2020, there is no proper solution for this issue. We have many workarounds though.

Here is the one I have been using, and one with less limitations in my opinion.

  1. Make your Realm Model Object classes conform to codable
class Dog: Object, Codable{
    @objc dynamic var breed:String = "JustAnyDog"
}
  1. Create this helper class
class RealmHelper {
    //Used to expose generic 
    static func DetachedCopy<T:Codable>(of object:T) -> T?{
       do{
           let json = try JSONEncoder().encode(object)
           return try JSONDecoder().decode(T.self, from: json)
       }
       catch let error{
           print(error)
           return nil
       }
    }
}
  1. Call this method whenever you need detached / true deep copy of your Realm Object, like this:
 //Suppose your Realm managed object: let dog:Dog = RealmDBService.shared.getFirstDog()
 guard let detachedDog = RealmHelper.DetachedCopy(of: dog) else{
    print("Could not detach Dog")
    return
 }
//Change/mutate object properties as you want
 detachedDog.breed = "rottweiler"

As you can see we are piggy backing on Swift's JSONEncoder and JSONDecoder, using power of Codable, making true deep copy no matter how many nested objects are there under our realm object. Just make sure all your Realm Model Classes conform to Codable.

Though its NOT an ideal solution, but its one of the most effective workaround.

like image 5
ImShrey Avatar answered Nov 10 '22 22:11

ImShrey