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)") } } }
Observe Query Results
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
The @ObservedResults property wrapper is intended for use in a SwiftUI View. If you want to observe results in a view model, register a change listener.
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.
Sort Observed Results
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
You cannot use a computed property as a SortDescriptor for @ObservedResults.
Observar los resultados seccionados
New in version 10.29.0.
You can observe a results set that is divided into sections by a key generated from a property on the object. We've added a computed variable to the model that we don't persist; we just use this to section the results set.
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() } } }
Observe App State
Si tu aplicación utiliza Atlas Device Sync, puedes observar el objeto aplicación para reaccionar a los cambios en el estado de inicio de sesión. Esto permite que tu aplicación realice operaciones mientras tenga un app.currentUser, o dirigir al usuario a iniciar sesión si no hay un app.currentUser.
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() } } }