【问题标题】:Remove property in Realm object移除 Realm 对象中的属性
【发布时间】:2015-06-09 10:57:41
【问题描述】:

我正在尝试删除我的一个 Realm 对象中的属性,但是我不确定如何为此编写迁移。

我刚刚从我的对象的头文件中删除了该属性,但由于我收到此错误,这不起作用:

由于未捕获的异常“RLMException”而终止应用程序,原因: '由于以下原因,对象类型'Stock'需要迁移 错误: - 最新对象模型中缺少属性“percentageOn”。'

我知道如何编写迁移添加字段,但如何删除?

【问题讨论】:

  • 当然你不能直接这样做而没有后果。解决方案 1:像 U 一样删除属性并从模拟器中删除应用程序。这解决了数据库不一致的问题。解决方案 2:您的应用正在生产中,并且用户已经在使用它。因此,您需要执行迁移以不影响您的客户。请阅读文档在这种情况下该怎么做:realm.io/docs/objc/latest/#migrations

标签: ios objective-c realm


【解决方案1】:

大卫说的是对的。如果您确保正确执行迁移,那么 Realm 可以轻松处理已删除和添加的属性。除非您实际上仍然需要 percentageOn 中的值,否则您甚至可以像 Realm 网站上的示例一样将迁移块留空:

// Inside your [AppDelegate didFinishLaunchingWithOptions:]

// Notice setSchemaVersion is set to 1, this is always set manually. It must be
// higher than the previous version (oldSchemaVersion) or an RLMException is thrown
[RLMRealm setSchemaVersion:1
            forRealmAtPath:[RLMRealm defaultRealmPath] 
        withMigrationBlock:^(RLMMigration *migration, NSUInteger oldSchemaVersion) {
  // We haven’t migrated anything yet, so oldSchemaVersion == 0
  if (oldSchemaVersion < 1) {
    // Nothing to do!
    // Realm will automatically detect new properties and removed properties
    // And will update the schema on disk automatically
  }
}];

// now that we have called `setSchemaVersion:withMigrationBlock:`, opening an outdated
// Realm will automatically perform the migration and opening the Realm will succeed
[RLMRealm defaultRealm];

【讨论】:

  • 好的,所以在迁移块中 Realm 检查是否有任何已删除的属性并将它们从数据库中删除?
  • 正确!话虽如此,这些属性中的数据也将被删除,因此如果您需要保留该数据,请确保将其移动到迁移块中的新属性中。
猜你喜欢
  • 1970-01-01
  • 2016-03-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多