Observar un objeto
El Swift SDK proporciona la Encapsulador de propiedades@ObservedRealmObject que invalida una vista cuando cambia un objeto observado. Puede usar este encapsulador de propiedades para crear una vista que se actualice automáticamente cuando cambia el objeto observado.
struct DogDetailView: View { var dog: Dog var body: some View { VStack { Text(dog.name) .font(.title2) Text("\(dog.name) is a \(dog.breed)") AsyncImage(url: dog.profileImageUrl) { image in image.resizable() } placeholder: { ProgressView() } .aspectRatio(contentMode: .fit) .frame(width: 150, height: 150) Text("Favorite toy: \(dog.favoriteToy)") } } }
Observar los resultados de la consulta
El SDK de Swift proporciona el contenedor de propiedades @ObservedResults, que permite observar una colección de resultados de consultas. Se puede realizar una escritura rápida en una colección ObservedResults y la vista se actualiza automáticamente cuando cambia la consulta observada. Por ejemplo, se puede eliminar un perro de una lista de perros observados usando onDelete.
Nota
El @ObservedResults contenedor de propiedad está diseñado para usarse en una vista de SwiftUI. Si desea observar los resultados en un modelo de vista, registre un detector de cambios.
struct DogsView: View { (Dog.self) var dogs /// The button to be displayed on the top left. var leadingBarButton: AnyView? var body: some View { NavigationView { VStack { // The list shows the dogs in the realm. // The ``@ObservedResults`` above implicitly opens a realm and retrieves // all the Dog objects. We can then pass those objects to views further down the // hierarchy. List { ForEach(dogs) { dog in DogRow(dog: dog) }.onDelete(perform: $dogs.remove) }.listStyle(GroupedListStyle()) .navigationBarTitle("Dogs", displayMode: .large) .navigationBarBackButtonHidden(true) .navigationBarItems( leading: self.leadingBarButton, // Edit button on the right to enable rearranging items trailing: EditButton()) }.padding() } } }
Tip
Para obtener más información sobre la sintaxis de consulta y los tipos de consultas que admite Realm, consulte: Leer - Swift SDK y Filtrar datos - Swift SDK.
Ordenar resultados observados
El contenedor de propiedad @ObservedResults puede tomar un parámetro SortDescriptor para ordenar los resultados de la consulta.
struct SortedDogsView: View { (Dog.self, sortDescriptor: SortDescriptor(keyPath: "name", ascending: true)) var dogs var body: some View { NavigationView { // The list shows the dogs in the realm, sorted by name List(dogs) { dog in DogRow(dog: dog) } } } }
Tip
No se puede utilizar una propiedad calculada como SortDescriptor para @ObservedResults.
Observar los resultados seccionados
Nuevo en la versión 10.29.0.
Se puede observar un conjunto de resultados dividido en secciones mediante una clave generada a partir de una propiedad del objeto. Hemos añadido una variable calculada al modelo que no se conserva; simplemente se usa para seccionar el conjunto de resultados.
var firstLetter: String { guard let char = name.first else { return "" } return String(char) }
Luego, podemos usar el contenedor de propiedad @ObservedSectionedResults para observar el conjunto de resultados dividido en secciones según la clave de la variable calculada.
(Dog.self, sectionKeyPath: \.firstLetter) var dogs
Puede utilizar estos resultados seccionados observados para completar una vista de lista dividida por secciones:
struct SectionedDogsView: View { (Dog.self, sectionKeyPath: \.firstLetter) var dogs /// The button to be displayed on the top left. var leadingBarButton: AnyView? var body: some View { NavigationView { VStack { // The list shows the dogs in the realm, split into sections according to the keypath. List { ForEach(dogs) { section in Section(header: Text(section.key)) { ForEach(section) { dog in DogRow(dog: dog) } } } } .listStyle(GroupedListStyle()) .navigationBarTitle("Dogs", displayMode: .large) .navigationBarBackButtonHidden(true) .navigationBarItems( leading: self.leadingBarButton, // Edit button on the right to enable rearranging items trailing: EditButton()) }.padding() } } }
Observar el estado de la aplicación
Si su aplicación usa Atlas Device Sync, puede observar cómo el objeto App reacciona a los cambios de estado de inicio de sesión. Esto permite que su aplicación realice operaciones mientras tenga un app.currentUser o que indique al usuario que inicie sesión si no tiene app.currentUser un.
Como Realm almacena en caché las credenciales de los usuarios en el dispositivo, tu aplicación puede funcionar sin conexión mientras tenga un app.currentUser.
/// This view observes the Realm app object. /// Either direct the user to login, or open a realm /// with a logged-in user. struct FlexibleSyncContentView: View { // Observe the Realm app object in order to react to login state changes. var app: RealmSwift.App var body: some View { if let user = app.currentUser { // Create a `flexibleSyncConfiguration` with `initialSubscriptions`. // We'll inject this configuration as an environment value to use when opening the realm // in the next view, and the realm will open with these initial subscriptions. let config = user.flexibleSyncConfiguration(initialSubscriptions: { subs in let peopleSubscriptionExists = subs.first(named: "people") let dogSubscriptionExists = subs.first(named: "dogs") // Check whether the subscription already exists. Adding it more // than once causes an error. if (peopleSubscriptionExists != nil) && (dogSubscriptionExists != nil) { // Existing subscriptions found - do nothing return } else { // Add queries for any objects you want to use in the app // Linked objects do not automatically get queried, so you // must explicitly query for all linked objects you want to include. subs.append(QuerySubscription<Person>(name: "people")) subs.append(QuerySubscription<Dog>(name: "dogs")) } }) OpenFlexibleSyncRealmView() .environment(\.realmConfiguration, config) } else { // If there is no user logged in, show the login view. LoginView() } } }