Reason: 'Object is already managed by another Realm. Use create instead to copy it into this Realm.'


I want to move some objects From one database to another

                for category in categorys {
                    try! userRealm.write {
                        userRealm.add(category, update: true)

the error:
reason: ‘Object is already managed by another Realm. Use create instead to copy it into this Realm.’

language:Swift 4.2

Looking forward to your help


That specific object is already being managed by Realm.

One options if you want to copy it to another Realm, create a new object, copy the properties over and save the new object in a different Realm.


I did exactly that.

        var config = Realm.Configuration(encryptionKey: Data.init(bytes: keyBytes, count: 64))
        config.fileURL = Bundle.main.url(forResource: "\(bookVersion)", withExtension: "realm")
        config.readOnly = true
        do {
            let realm = try Realm(configuration: config)
            // 创建数据库配置文件
            var userConfig = Realm.Configuration(encryptionKey:self.getRealmDataKey())
            let documentsDirectory = FileManager.default.urls(for:.documentDirectory, in: .userDomainMask)[0]
            userConfig.fileURL = documentsDirectory.appendingPathComponent("app2.realm")
            do {
                let userRealm = try Realm(configuration: userConfig)
                let categorys = realm.objects(XCategory.self)
                for category in categorys {
                    let c = XCategory()
                    category.categoryID = c.categoryID
                    category.categoryName = c.categoryName
                    category.categoryOrder = c.categoryOrder
                    try! userRealm.write {

But there is something wrong:
*** Terminating app due to uncaught exception ‘RLMException’, reason: ‘Primary key can’t be changed after an object is inserted.’


You can’t have duplicate primary keys - that’s the idea of a primary key - it makes the object unique. Let it create it’s own.