SwiftUI 应用程序显示领域更改但不显示新对象 [英] SwiftUI App Shows Realm Changes but Not New Objects

查看:54
本文介绍了SwiftUI 应用程序显示领域更改但不显示新对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Realm 10.7.3、Xcode 12.4、macOS 11.2.3

我正在试验 Realm 和 Combine+SwiftUI.当我在 Realm Studio 中更改我的数据时,它们会按预期立即反映在我的应用程序 UI 中.但是当我添加删除一个对象时,我的应用 UI 不会改变.

I am experimenting with Realm and Combine+SwiftUI. When I make changes to my data in Realm Studio, they immediately reflect in my app's UI as expected. But when I add or delete an object, my app UI does not change.

这是我的模型定义:

//--- Model ---
class Item: Object, ObjectKeyIdentifiable {
  @objc dynamic var _id = ObjectId.generate()
  @objc dynamic var text = ""
}

这是我的视图模型:

//--- View Model ---
class ItemModel: ObservableObject {
  static let shared = ItemModel()
  var token: NotificationToken? = nil
  @Published var items = [Item]()
  
  init(){
    let realm = try! Realm()
    let results = realm.objects(Item.self)
    items = Array(results)
   
    token = results.observe { [weak self] _ in
      print("-- updated --")
      self?.objectWillChange.send()
    }
  }
  
  deinit{
    token?.invalidate()
  }
}

最后,这是我的 SwiftUI 视图:

And last of all, here's my SwiftUI view:

//--- View ---
struct ItemView: View {
  @StateObject private var model = ItemModel.shared

  var body: some View {
    ScrollView{
      VStack(spacing: 7){
        ForEach(model.items, id: \._id) { item in
          Text(item.text)
        }
      }
    }
  }
}

任何想法为什么我的应用程序不会显示新的/删除的对象而只显示编辑?如果我重建我的应用程序,则会显示新的/删除的对象.

Any ideas why my app won't show new/deleted objects and only edits? If I rebuild my app, the new/deleted objects are shown.

推荐答案

Realm 结果对象是实时更新的对象,并且始终反映这些对象在 Realm 中的当前状态.

Realm Results objects are live-updating objects and always reflect the current state of those objects in Realm.

但是,如果您将 Realm 结果对象转换为数组

However, if you cast your Realm Results object to an array

items = Array(results)

它将那些对象与 Realm 断开连接,并且它们不再实时更新.

It 'disconnects' those objects from Realm and they are not longer live updating.

此外,Realm Results 对象是延迟加载的,这意味着它们仅在需要时才加载到内存中,因此数千个对象几乎不占用空间.

Additionally Realm Results objects are lazily-loaded, meaning that they are only loaded into memory when needed so thousands of objects take up almost no space.

将它们存储在一个数组中会改变 - 它们全部加载到内存中,可能会淹没设备.

Storing them in an array changes that - they are all loaded into memory and could overwhelm the device.

最佳实践是在整个使用过程中将 Realm 集合(结果、列表)保留为该类型的对象,而不是转换为数组.

Best practice is to leave Realm Collections (Results, Lists) as that type of object throughout the duration of using them instead of casting to an array.

这篇关于SwiftUI 应用程序显示领域更改但不显示新对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆