Как да промените атрибутите на клас, без да се налага да изтривате приложението чрез realm

В момента пиша програма в Swift, използвайки realm. Аз съм сравнително нов в разработката на iOS, но моето разбиране за realm е, че когато промените клас, съхраняван в realm, трябва да изтриете приложението от устройството, за да се отървете от постоянните данни. За съжаление въведох ръчно доста голяма база данни в приложението.

В момента трябва да променя името на атрибут в клас, но в бъдеще може да се наложи да добавя атрибути. Кой е най-добрият начин за актуализиране на хранилището на царството, така че да не се налага да изтривам приложението?

Ето един от моите модели:

class Device: Object {

   dynamic var name = ""
   dynamic var id = ""
   dynamic var os = ""
   dynamic var currentUser: User?
   dynamic var dateStamp = NSDate()
}

person pico0102    schedule 26.02.2016    source източник
comment
виждали ли сте областта за миграции в официалната документация?   -  person Anderson K    schedule 26.02.2016


Отговори (1)


Можете да добавите миграция, както се вижда в нашите документи и да я използвате за вземете старите стойности в ново свойство:

Обектив-C

// Inside your [AppDelegate didFinishLaunchingWithOptions:]

RLMRealmConfiguration *config = [RLMRealmConfiguration defaultConfiguration];
// Set the new schema version. This must be greater than the previously used
// version (if you've never set a schema version before, the version is 0).
config.schemaVersion = 1;

// Set the block which will be called automatically when opening a Realm with a
// schema version lower than the one set above
config.migrationBlock = ^(RLMMigration *migration, uint64_t oldSchemaVersion) {
    // We haven’t migrated anything yet, so oldSchemaVersion == 0
    if (oldSchemaVersion < 1) {
        // The -enumerateObjects:block: method iterates
        // over every Device object stored in the Realm file
        [migration enumerateObjects:Device.className
                      block:^(RLMObject *oldObject, RLMObject *newObject) {
            // e.g. Rename 'os' to 'operatingSystem'
            newObject[@"operatingSystem"] = oldObject[@"os"]
        }];
    }
};

// Tell Realm to use this new configuration object for the default Realm
[RLMRealmConfiguration setDefaultConfiguration:config];

// Now that we've told Realm how to handle the schema change, opening the file
// will automatically perform the migration
[RLMRealm defaultRealm];

Swift (с Realm Swift)

https://realm.io/docs/swift/latest/#performing-a-migration

// Inside your application(application:didFinishLaunchingWithOptions:)

let config = Realm.Configuration(
  // Set the new schema version. This must be greater than the previously used
  // version (if you've never set a schema version before, the version is 0).
  schemaVersion: 1,

  // Set the block which will be called automatically when opening a Realm with
  // a schema version lower than the one set above
  migrationBlock: { migration, oldSchemaVersion in
    // We haven’t migrated anything yet, so oldSchemaVersion == 0
    if (oldSchemaVersion < 1) {
        // The enumerate(_:_:) method iterates
        // over every Device object stored in the Realm file
        migration.enumerate(Device.className()) { oldObject, newObject in
            // e.g. Rename 'os' to 'operatingSystem'
            newObject["operatingSystem"] = oldObject["os"]
        }
    }
  })

// Tell Realm to use this new configuration object for the default Realm
Realm.Configuration.defaultConfiguration = config

// Now that we've told Realm how to handle the schema change, opening the file
// will automatically perform the migration
let realm = try! Realm()
person marius    schedule 29.02.2016