Firstly I use shared instance outside SwiftUI
let realm:Realm!
let container = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: ProjectSettings.group)!
static let shared = RealmDatabaseManager()
init(){
let defaultURL = Realm.Configuration.defaultConfiguration.fileURL
let realmURL = container.appendingPathComponent("default.realm")
//check if there's file in realmurl
let fileManager = FileManager.default
if !fileManager.fileExists(atPath: realmURL.path) {
try? fileManager.copyItem(at: defaultURL!, to: realmURL)
}
// Config init
let config = Realm.Configuration(fileURL: realmURL, schemaVersion: 9,migrationBlock: {migration,oldVersion in
if oldVersion < 3 {
migration.enumerateObjects(ofType: WordRecordRealm.className()) { oldObject, newObject in
//some works here
}
})
Realm.Configuration.defaultConfiguration = config
realm = try! Realm(configuration: config)
}
}
There is no error but the migration block never gets called when I change the schemaVersion.
Then I saw a way to write realm config into swiftui environment,and use @ObservedResuts and @ObservedRealmObject inside SwiftUI
var body: some Scene {
WindowGroup {
RouterView()
.environment(\.realmConfiguration, Realm.Configuration(fileURL: realmURL, schemaVersion: 32,migrationBlock: {migration,oldVersion in
//some works here
))
It is called normally. However, I want to hold a global instance of realm outside of SwiftUI View, so I still need to use the first block of code. But as long as I write the config same as the one in environment, the migration part in the environment will never be called again.
The weirdest thing is that at the time point that the migration block should be called, this shared instance is still not initialized. If I delete the schema version in the shared instance, the migration get called again but this shared instance doesn’t work cause the version mismatch.




