简体   繁体   中英

How to rename realm object in iOS

I am using realm in our iOS and Android app. For some reason i want to rename one of my realm object.

Initially we name the object Demo and now I want to change it to RealmDemo

In android we achieved it by using @RealmClass annotation

@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.

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'"

Two things.

First, You can name an object anything you want and change its name at any time.

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.

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.
  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.

Secondly, The other important thing is the name of the object is now RealmDemo , whereas the prior object is 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. Demo is still hanging around but is not referenced in your code so an error is thrown

On a possibly unrelated note, the className function references Demo

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

But the object name is RealmDemo.

It's not clear why the className function exists but it's not required or really needed. See the documentation for objects to get a feel for their structure - they may need a Primary Key

Seems like realm does not support className overriding for cocoa/ios.

https://github.com/realm/realm-cocoa/issues/2194

https://github.com/realm/realm-cocoa/issues/6624

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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