Update pre-populated Database while keeping data from a specific field


#1

Hello,

I got a pre-populated database for my app. Occasionally I’m going to be updating this pre-populated database with new data.
The problem is that the object contains a boolean field called “completed”. By default this field is false. When the user completes a certain task the object’s boolean field becomes true.
I want to find a way when migrating to the new pre-populated database to keep that boolean field the same as before.

Here is the code I have so far

        // copy over old data files
        let defaultURL = Realm.Configuration.defaultConfiguration.fileURL!
        let defaultParentURL = defaultURL.deletingLastPathComponent()
        
        if let v0URL = bundleURL("database") {
            //Delete if there's a file already
            do {
                try FileManager.default.removeItem(at: defaultURL)
                print("Item Removed")

            } catch {
                print("error removing seeds: \(error)")
            }
            
            //Copy the database file to the directory
            do {
                try FileManager.default.copyItem(at: v0URL, to: defaultURL)
                print("Item Copied")

            }catch {
                print("error copying seeds: \(error)")
            }
        }
        
        // define a migration block
        // you can define this inline, but we will reuse this to migrate realm files from multiple versions
        // to the most current version of our data model
        let migrationBlock: MigrationBlock = { migration, oldSchemaVersion in
            
            migration.enumerateObjects(ofType: BookModel.className()) { oldObject, newObject in
                // keep the old boolean completed value and assign it to the new one
                let completed = oldObject!["completed"] as! Bool
                newObject!["completed"] = completed
                print(completed)
            }
            
            print("Migration complete.")
        }
        
        Realm.Configuration.defaultConfiguration = Realm.Configuration(schemaVersion: 5, migrationBlock: migrationBlock)
        let realm = try! Realm()

        return true

I am suspecting that my code does not work because before migration happens, I have already deleted my previous database (which contains the user’s completed values). But how can I replace my previous database with the new one without delete-copy?

Thank you in advance!