境界创造有时会崩溃

时间:2017-02-03 06:35:31

标签: swift realm

为了创建我的领域实例,我创建了一个名为Realm Provider的类。不幸的是,它有时会在行中崩溃

return realm!

你能看出出现了什么问题以及为什么会这样吗?

class RealmProvider {

    private var realm: Realm?
    private let currentSchemaVersion: UInt64 = 6

    func loadRealm() -> Realm {

        if let realm = self.realm {
            return realm
        }

        migrateRealm()

        if let _ = NSClassFromString("XCTest"){
            realm =  try! Realm(configuration: Realm.Configuration(fileURL: nil, inMemoryIdentifier: "test", syncConfiguration: nil, encryptionKey: nil, readOnly: false, schemaVersion: currentSchemaVersion, migrationBlock: nil, deleteRealmIfMigrationNeeded: true, objectTypes: nil))
        } else {
            realm = try! Realm()
        }
        return realm!
    }

    private func migrateRealm() {

        Realm.Configuration.defaultConfiguration = Realm.Configuration(
            schemaVersion: currentSchemaVersion, migrationBlock: { _, oldSchemaVersion in

                if (oldSchemaVersion < self.currentSchemaVersion) {
                    self.purgeRealm()
                }
        })
    }

    private func purgeRealm() {
        logger.warning("deleting realm data...")
        do {
            if let realmUrl = Realm.Configuration.defaultConfiguration.fileURL {
                try FileManager.default.removeItem(at: realmUrl)
            }
        } catch {
            logger.error("failed deleting realm data")
        }
    }

}

0 个答案:

没有答案