Docs 菜单
Docs 主页
/ /
Atlas Device SDKs
/ /

在“SwiftUI 视图”之间传递 Realm 数据

在此页面上

  • 将 Realm 对象传递给视图
  • 传递环境值
  • 注入分区值
  • 注入已打开的 Realm
  • 注入 Realm 配置

Realm Swift SDK 提供了几种在视图之间传递 Realm 数据的方法:

  • 将 Realm 对象传递给视图

  • 使用环境注入:

    • 将分区值注入视图

    • 将打开的 Realm 注入到视图中

    • 将 Realm 配置注入视图

当您使用 @ObservedRealmObject@ObservedResults属性包装器时,您会隐式打开一个域并检索指定的对象或结果。然后,您可以将这些对象传递给层次结构中更下游的视图。

struct DogsView: View {
@ObservedResults(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()
}
}
}

环境 在使用 Realm 进行 SwiftUI 开发时,注入是一个有用的工具。Realm 属性包装器为您在开发 SwiftUI 应用程序时使用环境值提供了不同的方法。

如果您使用的是基于分区的同步,则可以使用环境注入来传递.partitionValue环境值。将其插入到执行@AsyncOpen@AutoOpen的视图中:

// If there is a logged in user, pass the user ID as the
// partitionValue to the view that opens a realm.
OpenPartitionBasedSyncRealmView().environment(\.partitionValue, user.id)

然后,当您使用属性包装器打开同步域时,请将partitionValue留为空字符串。属性包装器填充上面传入的环境对象的值。

// We can use an empty string as the partitionValue here because we're
// injecting the user.id as an environment value from the LoginView.
@AutoOpen(appId: YOUR_APP_SERVICES_APP_ID_HERE, partitionValue: "", timeout: 4000) var autoOpen

提示

迁移到 Flexible Sync

您可以自动将Atlas App Services Device Sync模式从基于分区的同步迁移到Flexible Sync 。 这样,您就可以利用更具表现力和更精细的 Flexible Sync 订阅和权限来管理用户可以读取和写入的同步数据。 有关更多信息,请参阅从基于分区的同步迁移到 Flexible Sync。

您可以将在另一个 SwiftUI 视图中打开的域作为环境值注入到视图中。属性包装器使用此传入的 Realm 来填充视图:

ListView()
.environment(\.realm, realm)

您可以通过在环境对象中传递不同的配置来使用默认 Realm 以外的 Realm。

LocalOnlyContentView()
.environment(\.realmConfiguration, Realm.Configuration( /* ... */ ))

后退

响应变更

来年

写入数据