Join us at MongoDB.local London on 7 May to unlock new possibilities for your data. Use WEB50 to save 50%.
Register now >
Docs Menu
Docs Home
/ /
Datos del modelo

Cambiar un modelo de objeto - SwiftUI

Nota

Modificar las propiedades del esquema de un dominio sincronizado

The following page demonstrates how to modify schema properties of a local realm. Learn how to modify schema properties of a synced realm.

Al actualizar el esquema de objetos, debe incrementar la versión del esquema y realizar una migración. Puede actualizar el esquema de objetos entre versiones principales de su aplicación.

For information on how to actually perform the migration, see: Change an Object Model.

Esta página se centra en cómo utilizar datos migrados en las vistas SwiftUI.

Para realizar una migración:

  • Update your schema and write a migration block, if required

  • Especifique Realm.Configuration que use esta lógica de migración y/o versión de esquema actualizada cuando inicialice su realm.

Desde aquí, tienes varias opciones para pasar el objeto de configuración. Puedes:

  • Establezca la configuración como predeterminada. Si no la pasa explícitamente mediante inyección de entorno o como parámetro, los contenedores de propiedades usarán la configuración predeterminada.

  • Use environment injection to provide this configuration to the first view in your hierarchy that uses Realm

  • Proporcione explícitamente la configuración a un contenedor de propiedades de Realm que toma un objeto de configuración, como @ObservedResults o @AsyncOpen.

Ejemplo

Por ejemplo, podría querer agregar una propiedad a un objeto existente. Podríamos agregar una propiedad favoriteTreat al objeto Dog en DoggoDB:

@Persisted var favoriteTreat = ""

Después de agregar la nueva propiedad al esquema, debe incrementar la versión del esquema. Tu Realm.Configuration podría verse así:

let config = Realm.Configuration(schemaVersion: 2)

Declare this configuration somewhere that is accessible to the first view in the hierarchy that needs it. Declaring this above your @main app entrypoint makes it available everywhere, but you could also put it in the file where you first open a realm.

Puedes establecer una configuración predeterminada en una aplicación SwiftUI, igual que en cualquier otra aplicación Swift de Realm. Para establecer la configuración predeterminada, asigna una nueva instancia de Realm.Configuration a la propiedad de clase Realm.Configuration.defaultConfiguration.

// Open the default realm
let defaultRealm = try! Realm()
// Open the realm with a specific file URL, for example a username
let username = "GordonCole"
var config = Realm.Configuration.defaultConfiguration
config.fileURL!.deleteLastPathComponent()
config.fileURL!.appendPathComponent(username)
config.fileURL!.appendPathExtension("realm")
let realm = try! Realm(configuration: config)

Once you have declared the configuration, you can inject it as an environment object to the first view in your hierarchy that opens a realm. If you are using the @ObservedResults or @ObservedRealmObject property wrappers, these views implicitly open a realm, so they also need access to this configuration.

.environment(\.realmConfiguration, config)

Si tu aplicación usa un reino local o sincronizado, la primera vista en la jerarquía que abre un reino varía dependiendo de si estás usando la aplicación con o sin sincronización.

Sin sincronización, puedes pasar el objeto de entorno de configuración del reino directamente a LocalOnlyContentView:

.environment(\.realmConfiguration, config)

Lo cual abre un reino implícito con:

struct LocalOnlyContentView: View {
// Implicitly use the default realm's objects(Dog.self)
@ObservedResults(Dog.self) var dogs
var body: some View {
if dogs.first != nil {
// If dogs exist, go to the DogsView
DogsView()
} else {
// If there is no Dog object, add one here.
AddDogView()
}
}
}

However, when your app uses Sync, you the Realm explicitly using the @AsyncOpen or @AutoOpen property wrapper:

/// This view opens a synced realm.
struct OpenFlexibleSyncRealmView: View {
// We've injected a `flexibleSyncConfiguration` as an environment value,
// so `@AsyncOpen` here opens a realm using that configuration.
@AsyncOpen(appId: flexibleSyncAppId, timeout: 4000) var asyncOpen
var body: some View {
switch asyncOpen {
// Starting the Realm.asyncOpen process.
// Show a progress view.
case .connecting:
ProgressView()
// Waiting for a user to be logged in before executing
// Realm.asyncOpen.
case .waitingForUser:
ProgressView("Waiting for user to log in...")
// The realm has been opened and is ready for use.
// Show the content view.
case .open(let realm):
// Do something with the realm
UseRealmView(realm: realm)
// The realm is currently being downloaded from the server.
// Show a progress view.
case .progress(let progress):
ProgressView(progress)
// Opening the Realm failed.
// Show an error view.
case .error(let error):
ErrorView(error: error)
}
}
}

Por lo tanto, debe pasar el objeto de entorno a la vista que abre explícitamente el dominio. En este caso, OpenFlexibleSyncRealmView.

Lo importante a recordar es asegurarse de pasar el Realm.Configuration que abarca su lógica de migración a cualquier jerarquía de vistas que abra implícita o explícitamente un reino.

Puedes pasar explícitamente el objeto de configuración a un contenedor de propiedades de Realm SwiftUI que acepte un objeto de configuración, como @ObservedResults o @AutoOpen. En este caso, podrías pasarlo directamente a @ObservedResults en nuestro DogsView.

// Use a `config` that you've passed in from above.
@ObservedResults(Dog.self, configuration: config) var dogs

Volver

Realm Object Models

En esta página