我有一个对象NotSureItem,其中有三个属性title,其名称从我后来添加的texttextDescription重命名,还有一个dateTime属性.现在,当我要运行我的应用程序时,当我想向这些属性添加内容时,它会崩溃.下面的语句显示了它.

'Migration is required for object type 'NotSureItem' due to the following errors:
- Property 'text' is missing from latest object model.
- Property 'title' has been added to latest object model.
- Property 'textDescription' has been added to latest object model.'

这是我的代码:

import Foundation
import Realm

class NotSureItem: RLMObject {
    dynamic var title = ""   // renamed from 'text'
    dynamic var textDescription = "" // added afterwards
    dynamic var dateTime = NSDate()
}

推荐答案

As long as you have not released your app你可以简单地删除你的应用程序并再次运行.

每次更改领域对象的属性时,现有数据库都会与新数据库不兼容.

只要你还在开发阶段,你就可以简单地从模拟器/设备中删除应用程序,然后重新启动.

如果要更改对象的属性,则必须实现到新数据库版本的migrations.

要实际执行迁移,需要实现一个领域迁移块.通常,您会将块添加到application(application:didFinishLaunchingWithOptions:):

var configuration = Realm.Configuration(
    schemaVersion: 1,
    migrationBlock: { migration, oldSchemaVersion in
        if oldSchemaVersion < 1 {

            // if just the name of your model's property changed you can do this 
            migration.renameProperty(onType: NotSureItem.className(), from: "text", to: "title")

            // if you want to fill a new property with some values you have to enumerate
            // the existing objects and set the new value
            migration.enumerateObjects(ofType: NotSureItem.className()) { oldObject, newObject in
                let text = oldObject!["text"] as! String
                newObject!["textDescription"] = "The title is \(text)"
            }

            // if you added a new property or removed a property you don't
            // have to do anything because Realm automatically detects that
        }
    }
)
Realm.Configuration.defaultConfiguration = configuration

// opening the Realm file now makes sure that the migration is performed
let realm = try! Realm()

每当你的方案改变时,你必须增加迁移块中的schemaVersion,并更新块中所需的migrations.

Swift相关问答推荐

如何在SWIFT中使用DiscardingTaskGroup获得任务结果

格式化单位和度量值.为什么从符号初始化的单位不能产生与静态初始化相同的结果

从后台线程获取@发布属性的值(不更改它)是正确的吗?

在一行语句中比较Date.now的相等性是否安全

Xcode 15 Beta中如何使用@Observable?

为什么我在我的 Swift iOS 应用程序项目中收到 Xcode 中的错误消息无法识别的 Select 器发送到类?

我如何遵守与演员的协议?

Swift-SceneKit-无法从art.scnassets加载.scn文件

为 SwiftUI 中的属性提供默认值

RxSwift 事件触发了两次

从 Swift 列表中的行中检索值

`IndexSet` 永远不会是空的?

SwiftUI 文本被意外截断

Apple 的自然语言 API 返回意外结果

在运行时访问 UIView 宽度

在 Swift 中计算两个日期之间的差异

为什么 swift 中的类没有存储类型属性?

如何为多个类 Swift 进行扩展

如何停止 NSTimer.scheduledTimerWithTimeInterval

枚举大小写的原始值必须是文字