How can I avoid migration in RealmSwift
There are two ways to skip migration error regardless schema changes.
Use
deleteRealmIfMigrationNeeded
property. If it istrue
, recreate the Realm file with the provided schema if a migration is required.let config = Realm.Configuration(deleteRealmIfMigrationNeeded: true)
Realm.Configuration.defaultConfiguration = config
let realm = try! Realm()
...Increment schema version every launch. Realm has auto migration feature. If you don't need to migrate existing data, you can just increment schema version. Schema will be changed by Realm automatically.
let config = Realm.Configuration(schemaVersion: try! schemaVersionAtURL(Realm.Configuration.defaultConfiguration.fileURL!) + 1)
Realm.Configuration.defaultConfiguration = config
let realm = try! Realm()
...
Unable to do a Realm migration in Swift
This exception will be thrown when stored data doesn’t match the model you have in code.
You shouldn’t need to do anything in the migration block, however you will need to trigger a migration by updating the value of Realm.Configuration.schemaVersion
, e.g.:
schemaVersion: 3,
Realm Migration: Migrating objects to another
You don't need to do anything with LinkingObjects
, realm calculates those automatically when you query them.
All you'll need to do in your migration is set media
to be a new Media
object with the values you already have.
Other notes:
- The second
enumerateObjects
isn't needed. - You can remove
image
,coverImage
, andvideo
fromItem
since you're moving those value toMedia
Edit: This is what you would need to have in your migration.
let media = Media()
media.fullImage = oldItem?["image"] as! String
media.thumbnailImage = oldItem?["coverImage"] as! String
media.video = oldItem?["video"] as! String
newItem?["media"] = media
How to keep certain changed properties unchanged in Realm migration - Swift
I figured it out. You have to do a partial serialization.
Changed this:
realm.add(thing, update: .modified)
To:
realm.create(Thing.self, value: [
"id": thing.id,
"propertyOne": thing.propertyOne
// Leave out propertyTwo to leave it unchanged
], update: .modified)
Understanding migrations in Realm - Swift
No, in this case you don't need to perform a migration. You only need to perform a migration in case existing objects need to be changed (adding/removing properties of existing Realm model classes).
If you add a new class to Realm, you don't need to perform a migration.
In most cases, Realm can automatically perform the migration and all you need to do is increase your schema version by 1. However, if you are for example combining two existing properties into a new one, you need to handle that manually in your migration block.
Detect if Realm.io db needs migration - if so, destroy it
This has been working like a charm for me since Swift 2 introduced try/catch. I just call testRealmFile()
from my app delegate at launch, and all is cool after that.
func testRealmFile(){
do {
try Realm().objects(Model1)
try Realm().objects(Model2)
} catch {
print("can't access realm, migration needed")
deleteRealmFile()
}
}
func deleteRealmFile(){
if let path = Realm.Configuration.defaultConfiguration.path {
do{
try NSFileManager.defaultManager().removeItemAtPath(path)
print("realm file deleted")
} catch {
print("no realm file to delete")
}
}
}
Swift Realm migration create reference from old type to new one
After long testing and trying different possibilities I managed to migrate the data.
Here is what I did to accomplish this.
I used this as a base:
class RealmMigrationObject {
let migration: () -> ()
init(migration: @escaping () -> ()) {
self.migration = migration
}
}
and derived classes from that. Something like:
class MigrationObjectToThree: RealmMigrationObject {
init() {
super.init(migration: MigrationObjectToThree.migration)
}
private static func migration() {
print("Migration to three | migration")
var imageInfos: [ImageInfo] = []
let config = Realm.Configuration(schemaVersion: 3, migrationBlock: { migration, oldSchemaVersion in
print("Migration to three | migrationBlock")
print("RealmMigration: Applying migration from \(oldSchemaVersion) to 3")
migration.deleteData(forType: "ExploreSectionObjectRealm")
migration.enumerateObjects(ofType: "ImageInfoRealm") { oldInfo, newObject in
guard let oldInfo = oldInfo else {
return
}
guard let id = oldInfo["id"] as? String,
let url = oldInfo["url"] as? String,
let url500 = oldInfo["url500"] as? String,
let url400 = oldInfo["url400"] as? String,
let url300 = oldInfo["url300"] as? String,
let url200 = oldInfo["url200"] as? String,
let url100 = oldInfo["url100"] as? String,
let colorString = oldInfo["color"] as? String,
let color = UIColor(hexString: colorString) else {
return
}
imageInfos.append(ImageInfo(id: id,
url: url,
url500: url500,
url400: url400,
url300: url300,
url200: url200,
url100: url100,
color: color))
}
})
Realm.Configuration.defaultConfiguration = config
do {
let realm = try Realm(configuration: config)
print("Realm is located at: \(realm.configuration.fileURL?.description ?? "")")
print(realm.configuration.fileURL?.description ?? "") // Printing here on purpose as it's easier to copy
} catch {
print("Realm Error: \(error), trying to rebuild realm from scratch")
let deleteMigrationConfig = Realm.Configuration(schemaVersion: RealmHelper.schemaVersion,
deleteRealmIfMigrationNeeded: true)
do {
_ = try Realm(configuration: deleteMigrationConfig)
} catch {
print("Failed to instantiate: \(error.localizedDescription)")
}
}
RealmHelper.removeRealmFiles()
Realm.Configuration.defaultConfiguration = Realm.Configuration(schemaVersion: 3)
imageInfos.forEach({ $0.save() })
}
}
From that I just created all migration for the difference between the current schema version and target schema version on looped over all migrations simply executing the migration
function of that given object.
Realm migration not called
If you write let realm = try! Realm()
in a view controller as an instance variable, it will be called before application: didFinishLaunchingWithOptions
from Storyboard. To resolve this, you can use lazy var realm = try! Realm()
instead. lazy
defers creating an instance variable until the variable is accessed.
Related Topics
Trying to Use Keychainitemwrapper by Apple "Translated" to Swift
Vapor 3 Beta Example Endpoint Request
Add Shadow Above Swiftui's Tabview
Can/How to Replace My Kvo Stuff with Rc3
Check If Variable Is a Block/Function/Callable in Swift
How to Get Motion Events with the Apple Tv Remote
How to Extract Image from Lplinkview in Linkpresentation Framework
Making Cocoa Application Scriptable Swift
Swift: How to Open File with Associated Application
How Safe Are Swift Collections When Used with Invalidated Iterators/Indices
Nsurlsession/Nsurlconnection Http Load Failed (Kcfstreamerrordomainssl, -9802)
How to Use Environment Map in Arkit
Sending Whatsapp Message to a Specific Contact Number (Swift Project)
How to Check If an Email Address Is Already in Use Firebase
Accessing Multiple Audio Hardware Outputs/Channels Using Avfoundation and Swift