0
votes

I have two realm files in one App, something wrong when I wanna migrate them. I want realm update automatically when run in Xcode while does not change the schemaVersion every time.

class News: Object {
    @objc dynamic var name: String  
}

class NewsManager {
    static var realm = try! Realm()
    static var cacheRealm: Realm = {

        let documentDirectory = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask,
                                                         appropriateFor: nil, create: false)
        let url = documentDirectory.appendingPathComponent("cache.realm")
        var config = Realm.Configuration()
        config.fileURL = url
        return try! Realm(configuration: config)
    }()
}

When I add a new property to News such as @objc dynamic var title: String, I add the following code in AppDelegate func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey : Any]? = nil) -> Bool

let config = Realm.Configuration(schemaVersion: 1, migrationBlock: { migration, oldSchemaVersion in

    })
Realm.Configuration.defaultConfiguration = config

The message on crash at return try! Realm(configuration: config) in NewsManager.

Fatal error: 'try!' expression unexpectedly raised an error: Error Domain=io.realm Code=10 "Migration is required due to the following errors:
- Property 'News.test' has been added." UserInfo={Error Code=10, NSLocalizedDescription=Migration is required due to the following errors:
- Property 'News.test' has been added.}: file /BuildRoot/Library/Caches/com.apple.xbs/Sources/swiftlang/swiftlang-900.0.69.2/src/swift/stdlib/public/core/ErrorType.swift, line 181

What should I do?

Realm: 3.0.1

Swift: 4.0

iOS : 10

2

2 Answers

0
votes

Realm is working as expected. Some types of model changes Realm can migrate automatically, others require you to provide a manual migration. The one in your example is one of them.

Since you added a new, non-optional property of type String, Realm needs to go through all your existing models and figure out what to put in that property. If the property were type String?, it would make sense to use nil as a default value, and Realm could carry out the migration automatically. However, since the type is String and there's no obvious sensible default, Realm requires you to manually specify a value for the new property for each model object.

The right way to fix this "problem" is to increment your schema number and provide a migration block that actually specifies the new values for new properties whenever you change your model in a way that requires a migration.

Please review our documentation on migrations for more details.

0
votes

Check it out https://realm.io/docs/swift/latest/#migrations. Realm site is very good for understanding how properly use Realm in your projects