ios - 在交互式 UI 上保存 Realm 对象

标签 ios database swift nsoperationqueue realm

我有一个表格 View ,一旦单元格即将可见,我就加载它的图像。加载图像时,保存其 NSData(继承自 Object)的模型应写入数据库。

我试过两种方法:

  1. 等到所有图片加载完毕,然后将数据写入 数据库。
  2. 将每个加载图像的模型写入数据库。

第一个需要滚动整个 TableView (如果我们延迟加载图像)或在 viewDidLoad() 上加载图像,这也不是最佳选择。 第二种方法很好,一旦加载图像,它的模型最终就会更新。但是 Realmwrite() 函数上卡住了 UI。

我曾尝试使用异步主队列进行写入,但这会在每次 Realm 执行写入操作时产生短暂的故障。我还尝试使用 UserInitiated 异步队列,但这只会导致我的应用程序崩溃...

    let queue = NSOperationQueue()
    queue.qualityOfService = .UserInitiated

    // this code is executed on imageDidLoad()
    queue.addOperationWithBlock {
          let realm = Realm()
          realm.refresh()
          realm.write {
                realm.add(downloadable!, update: true)
          }
    }

结果我得到:

*** Terminating app due to uncaught exception 'RLMException', reason: 'Object is already persisted in a Realm'

可能的解决方案是什么?

最佳答案

如果没有更多的上下文很难判断,但看起来 downloadable 已经是一个持久化的 Object,所以尝试在另一个线程上使用它实际上是行不通的。如果 downloadable 有一个主键,您可能想改用它,执行类似于以下操作的操作:

let queue = NSOperationQueue()
queue.qualityOfService = .UserInitiated

let primaryKey = downloadable.primaryKey

// this code is executed on imageDidLoad()
queue.addOperationWithBlock {
      let realm = Realm()
      realm.refresh()
      realm.write {
            realm.create(DownloadableClass.Self, value: ["primaryKey" : primaryKey, "imageData" : imageData], update: true)
      }
}

关于ios - 在交互式 UI 上保存 Realm 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31643333/

相关文章:

iphone - 代表似乎自动设置为零

ios - UICollectionView:将点击手势识别器添加到 collectionView super View

database - MongoDB 中的所有查询都是临时的吗?

MySQL:MySQL 5.5 中会提供面向列的引擎吗?

arrays - 是否可以在数组中快速访问数组中的字符串?

ios - navigationController 在执行 segue 时为零?

ios - 为 cgsize 添加 uiColor (swift3)

ios - iOS 中的 UIPickerView 中的 UITableView

ios - 具有不同记录和 UIPickerView 的 NSFetchRequest

c# - 如何在 Asp.net MVC 中实现对象数据库