Как изменить атрибуты класса без необходимости удалять приложение с помощью области

В настоящее время я пишу программу на Swift, используя область. Я новичок в разработке iOS, но мое понимание области таково: когда вы меняете класс, хранящийся в области, вам нужно удалить приложение с устройства, чтобы избавиться от сохраняемых данных. К сожалению, я вручную ввел в приложение довольно большую базу данных.

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

Вот одна из моих моделей:

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];

Свифт (с 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