shouldCompactOnLaunch加上已定义的迁移块,无法迁移已经打开的领域

时间:2019-05-07 06:36:52

标签: swift realm realm-mobile-platform realm-migration

我正在尝试缩小领域数据库的大小。我的didFinishLaunchingWithOptions中有以下配置:

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    var config = Realm.Configuration(shouldCompactOnLaunch: { totalBytes, usedBytes in
            // totalBytes refers to the size of the file on disk in bytes (data + free space)
            // usedBytes refers to the number of bytes used by data in the file

            // Compact if the file is over 100MB in size and less than 50% 'used'
            let oneHundredMB = 100 * 1024 * 1024
            return (totalBytes > oneHundredMB) && (Double(usedBytes) / Double(totalBytes)) < 0.5
        })

        do {
            // Realm is compacted on the first open if the configuration block conditions were met.
            _ = try Realm(configuration: config)
        } catch let err as NSError {
            // handle error compacting or opening Realm
            print("%%%%%%%%%%%%% in the catch \(err.localizedDescription)   !!!! %%%%%%%%%%%%%%")
        }

        config = checkForMigration(currently: config);
        // other stuff
        // calling methods which clear out some base64strings to url paths in some realm tables
        return true
   }

checkForMigration如下所示:

func checkForMigration(currently config: Realm.Configuration) -> Realm.Configuration
    {
        var configu = config;
        var needsMigration: Bool = false;
        if util_Migration.schemaVersion != configu.schemaVersion
        {
            configu.schemaVersion = util_Migration.schemaVersion
            configu.migrationBlock = util_Migration.migration
            needsMigration = true;
        }

        Realm.Configuration.defaultConfiguration = configu

        if needsMigration {

            do { try Realm.performMigration()}
            catch let err as NSError
            {
                print("Realm Migration Error::: \(err.localizedDescription)");
            }
        }
        return configu;
    }

1。。如何修改它以同时配置迁移块和启动时的压缩?

现在,如果从以前的版本升级,则我的应用程序可以工作,但全新安装时不可以。重新安装时出现此错误:

Cannot migrate Realms that are already open

当我刚刚传入config = Realm.Configuration()

时,我的迁移方法始终有效

2。。该添加什么?有什么地方可能出问题吗,我们需要在这个问题中加以解决?

3。。有没有理由不使用更严格的规则进行优化?例如如果少于80个使用了?

0 个答案:

没有答案