ios - 如何在一个应用程序中迁移多个 Realm 文件

标签 ios swift realm

我在一个应用程序中有两个 Realm 文件,当我想迁移它们时出现问题。我希望在 Xcode 中运行时自动更新 Realm ,而不是每次都更改 schemaVersion

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)
    }()
}

当我向新闻添加新属性时,例如@objc动态var title:String, 我在 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

返回尝试时出现崩溃消息! NewsManager 中的 Realm (配置:config)。

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

我应该做什么?

Realm :3.0.1

swift :4.0

iOS:10

最佳答案

Realm 正在按预期运行。某些类型的模型更改 Realm 可以自动迁移,而其他类型的模型更改则需要您提供手动迁移。您的示例中的就是其中之一。

由于您添加了一个 String 类型的新的非可选属性,Realm 需要遍历所有现有模型并找出要在该属性中放入的内容。如果属性的类型为String?,则使用nil作为默认值是有意义的,并且Realm可以自动执行迁移。但是,由于类型是 String 并且没有明显合理的默认值,因此 Realm 要求您手动为每个模型对象的新属性指定一个值。

解决此“问题”的正确方法是增加架构编号并提供一个迁移 block ,每当您以需要迁移的方式更改模型时,该迁移 block 实际上会指定新属性的新值。

请查看我们的documentation on migrations了解更多详情。

关于ios - 如何在一个应用程序中迁移多个 Realm 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47070443/

相关文章:

ios - 有没有办法获取 iOS 应用程序的所有 View Controller 的类名?

iOS SDK-如何获取 viewController 的 segue 标识符?

swift - Firebase 按顺序获取数据

ios - addNotificationBlock { RealmCollectionChange } 在 UITableView 中崩溃

iphone - 从 NSDictionary 中提取 CGFloat 的语法

iphone - 为几个ios版本导入 header ?

ios - 如何让背景音乐继续播放?

ios - 通过解析将时间戳添加到 MapView 注释?

swift - 了解 Realm 对象服务器上的用户

ios - 在 Swift 中测试基于 Realm 的框架