简体   繁体   English

如何在 iOS 中重命名 realm object

[英]How to rename realm object in iOS

I am using realm in our iOS and Android app.我在我们的 iOS 和 Android 应用程序中使用 realm。 For some reason i want to rename one of my realm object.出于某种原因,我想重命名我的 realm object 之一。

Initially we name the object Demo and now I want to change it to RealmDemo最初我们将其命名为 object Demo ,现在我想将其更改为RealmDemo

In android we achieved it by using @RealmClass annotation在 android 中,我们使用@RealmClass 注解实现了它

@RealmClass(name = "Demo")
open class RealmDemo : RealmObject() {
}

On iOS side i am not sure how exactly i can do similar as i did in android.在 iOS 方面,我不确定我如何能像在 android 中那样做类似的事情。

class RealmDemo: Object {
    override static func className() -> String {
        "Demo"
    }
}

I tried above ^ but getting following error "Terminating app due to uncaught exception 'RLMException', reason: 'Object type 'Demo' not managed by the Realm'"我在上面尝试过^,但出现以下错误“由于未捕获的异常'RLMException'而终止应用程序,原因:'对象类型'Demo'不由领域管理'”

Two things.两件事情。

First, You can name an object anything you want and change its name at any time.首先,您可以随意命名 object 并随时更改其名称。

HOWEVER, that's a destructive change, and Realm doesn't have any way to know the the newly named object 'is the same object' as the prior object.然而,这是一个破坏性的变化,Realm 没有任何办法知道新命名的 object 与之前的 object“是同一个对象”。

How that's handled depends on what the use case is:如何处理取决于用例是什么:

  1. If this is a development situation, delete your local Realm files and run the app and the object with the new name will be created automatically.如果这是开发情况,请删除您本地的 Realm 文件并运行该应用程序,将自动创建具有新名称的 object。
  2. If this is production then a migration block is needed (as on any platform) to migrate the data from the old object to the new one.如果这是生产,则需要一个迁移块(如在任何平台上)将数据从旧的 object 迁移到新的。

Secondly, The other important thing is the name of the object is now RealmDemo , whereas the prior object is Demo其次,另一个重要的是 object 现在的名称是RealmDemo ,而之前的 object 是Demo

class RealmDemo: Object {

so technically those are two separate objects.所以从技术上讲,它们是两个独立的对象。 To Realm, you've abandoned the Demo object totally and that's a destructive change.对于 Realm,您完全放弃了 Demo object,这是一个破坏性的变化。 Demo is still hanging around but is not referenced in your code so an error is thrown Demo 仍然存在,但未在您的代码中引用,因此会引发错误

On a possibly unrelated note, the className function references Demo在一个可能不相关的注释上,className function 引用了 Demo

override static func className() -> String {
   "Demo"
}

But the object name is RealmDemo.但是 object 名称是 RealmDemo。

It's not clear why the className function exists but it's not required or really needed.目前尚不清楚为什么className function 存在,但它不是必需的或真正需要的。 See the documentation for objects to get a feel for their structure - they may need a Primary Key请参阅对象的文档以了解它们的结构 - 它们可能需要主键

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM