tipos son segun onu migrantes migracion los humanos derechos cuales consecuencias causas ios swift realm

ios - son - migracion segun la onu



RLMException, se requiere la migraciĆ³n para el tipo de objeto (6)

Tengo un objeto NotSureItem en el que tengo tres title propiedades cuyo nombre se renombra de text y textDescription que agregué más tarde y una propiedad dateTime . Ahora, cuando voy a ejecutar mi aplicación, se bloquea cuando quiero agregar algo a estas propiedades. Muestra las siguientes afirmaciones.

''Migration is required for object type ''NotSureItem'' due to the following errors: - Property ''text'' is missing from latest object model. - Property ''title'' has been added to latest object model. - Property ''textDescription'' has been added to latest object model.''

Aquí está mi código:

import Foundation import Realm class NotSureItem: RLMObject { dynamic var title = "" // renamed from ''text'' dynamic var textDescription = "" // added afterwards dynamic var dateTime = NSDate() }


Solo incrementa la versión del esquema.

Realm detectará automáticamente nuevas propiedades y propiedades eliminadas

var 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: 2, // 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) { // Nothing to do! // Realm will automatically detect new properties and removed properties // And will update the schema on disk automatically } }) do{ realm = try Realm(configuration: config) print("Database Path : /(config.fileURL!)") }catch{ print(error.localizedDescription) }


El código de abajo funciona para mí

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { RLMRealmConfiguration *config = [RLMRealmConfiguration defaultConfiguration]; config.schemaVersion = 2; config.migrationBlock = ^(RLMMigration *migration, uint64_t oldSchemaVersion) { // The enumerateObjects:block: method iterates // over every ''Person'' object stored in the Realm file [migration enumerateObjects:Person.className block:^(RLMObject *oldObject, RLMObject *newObject) { // Add the ''fullName'' property only to Realms with a schema version of 0 if (oldSchemaVersion < 1) { newObject[@"fullName"] = [NSString stringWithFormat:@"%@ %@", oldObject[@"firstName"], oldObject[@"lastName"]]; } // Add the ''email'' property to Realms with a schema version of 0 or 1 if (oldSchemaVersion < 2) { newObject[@"email"] = @""; } }]; }; [RLMRealmConfiguration setDefaultConfiguration:config]; // now that we have updated the schema version and provided a migration block, // opening an outdated Realm will automatically perform the migration and // opening the Realm will succeed [RLMRealm defaultRealm]; return YES; }

Más información: https://realm.io/docs/objc/latest/#getting-started


Eliminar la aplicación y volver a instalarla no es una buena práctica. Debemos incorporar algunos pasos de migración durante el desarrollo desde la primera vez que nos encontramos con la necesidad de migración. El enlace proporcionado por SilentDirge es bueno: documento de migración de reino , que proporciona buenos ejemplos para manejar diferentes situaciones.

Para una tarea de migración mínima, el siguiente fragmento de código del enlace anterior puede realizar la migración automáticamente y se utilizará con el método disFinishLaunchWithOptions de AppDelegate:

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) { // Nothing to do! // Realm will automatically detect new properties and removed properties // And will update the schema on disk automatically } }) // 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 _ = try! Realm()


Puede borrar la base de datos en el lanzamiento de esta manera:

[[NSFileManager defaultManager] removeItemAtURL:[RLMRealmConfiguration defaultConfiguration].fileURL error:nil];


Su base de datos modificada ya no es compatible con la base de datos guardada, por lo que se requiere una migración. Sus opciones son eliminar el archivo de base de datos anterior y comenzar de nuevo (funciona bien si está en la fase inicial de desarrollo), o si está activo, realice la migración.

Para ello, defina una versión de esquema y proporcione un "script" de migración de base de datos dentro de su configuración de Realm. El proceso completo se documenta aquí (junto con ejemplos de código): aquí


Mientras no haya lanzado su aplicación , simplemente puede eliminarla y ejecutarla nuevamente.

Cada vez que cambia las propiedades en sus objetos de Reino, su base de datos existente se vuelve incompatible con la nueva.

Mientras esté en la etapa de desarrollo, simplemente puede eliminar la aplicación del simulador / dispositivo y volver a iniciarla.

Más adelante, cuando se haya lanzado su aplicación y cambie las propiedades de sus objetos, tendrá que implementar una migración a la nueva versión de la base de datos.

Para realizar realmente una migración, se implementa un bloque de migración de Reino. Por lo general, agregaría el bloque a la application(application:didFinishLaunchingWithOptions:) :

var configuration = Realm.Configuration( schemaVersion: 1, migrationBlock: { migration, oldSchemaVersion in if oldSchemaVersion < 1 { // if just the name of your model''s property changed you can do this migration.renameProperty(onType: NotSureItem.className(), from: "text", to: "title") // if you want to fill a new property with some values you have to enumerate // the existing objects and set the new value migration.enumerateObjects(ofType: NotSureItem.className()) { oldObject, newObject in let text = oldObject!["text"] as! String newObject!["textDescription"] = "The title is /(text)" } // if you added a new property or removed a property you don''t // have to do anything because Realm automatically detects that } } ) Realm.Configuration.defaultConfiguration = configuration // opening the Realm file now makes sure that the migration is performed let realm = try! Realm()

Siempre que su esquema cambie, debe aumentar la schemaVersion en el bloque de migración y actualizar la migración necesaria dentro del bloque.