レルム データベースを移行し、スキーマ バージョンを設定する、文書化された方法の 1 つを使用しようとしています。私が使用しているコードの種類は次のとおりです。
let config = Realm.Configuration(
// Set the new schema version. This must be greater than the previously used
// version (if you've never set a schema version before, the version is 0).
schemaVersion: 1,
// Set the block which will be called automatically when opening a Realm with
// a schema version lower than the one set above
migrationBlock: { migration, oldSchemaVersion in
// We haven’t migrated anything yet, so oldSchemaVersion == 0
if (oldSchemaVersion < 1) {
// Nothing to do!
// Realm will automatically detect new properties and removed properties
// And will update the schema on disk automatically
}
})
// Tell Realm to use this new configuration object for the default Realm
Realm.Configuration.defaultConfiguration = config
これはかなり標準的なコードのようで、他の人が使用しているようです。ただし、私をつまずかせているように見えるのは、レルムインスタンスを初期化しているところです。これにより、スキーマ設定が設定または永続化されません。
私が苦労しているのは、次のコードをどこに設定するかです:
let uiRealm = try! Realm()
- これを @UIApplicationMain の上の AppDelegate の上部に配置すると、初期化が早すぎます
- 移行後に関数を呼び出す予定のコントローラーファイルを作成し、その先頭にイニシャライザーを配置すると、まだ機能しません
以下のコードのように ViewController のクラス内に配置すると、エラー Instance member uiRealm cannot be used on type XYZViewController が表示されます
import UIKit import RealmSwift class XYZViewController: UITableViewController,UIPickerViewDataSource,UIPickerViewDelegate { let uiRealm = try! Realm() var scenarios = uiRealm.objects(Scenario).filter("isActive = true ") }
だから私の質問は、どこで初期化するか、どのように移行するのが最善かについてのベストプラクティスはありますか?