ios - 为什么我们在核心数据中使用performWait?

标签 ios swift core-data semaphore

据我们所知

  • performWait 函数同步执行上下文队列中的给定 block 。
  • 执行函数异步执行上下文队列中的给定 block 。

在我的项目中,我使用 performWait 函数来获取数据,因为我希望调用线程在返回之前等到 block 执行完毕。这是实现它的最简单方法。但后来我意识到 performWait 的工作速度很慢。然后我尝试用信号量实现自己的同步并使用 perform 函数。以下是结果:

执行等待

    let currentTime1 = getCurrentMillis()
    context?.performAndWait({
        ....
    })
    let currentTime2 = getCurrentMillis()
    let diff = currentTime2 - currentTime1
    print("getActivities diff: " + String(diff))

执行信号量

    let currentTime1 = getCurrentMillis()
    let semaphore = DispatchSemaphore(value: 0)
    context?.perform({
       ....
       semaphore.signal()
    })
    semaphore.wait()
    let currentTime2 = getCurrentMillis()
    let diff = currentTime2 - currentTime1
    print("getActivities diff: " + String(diff))

getActivities 差异:1248 毫秒

getActivitiesWithSemaphore 差异:90 毫秒

好的,我知道这更容易。但是,为什么这么慢?将它用于 perform 函数还有哪些其他优势?

最佳答案

The perform(_:) method treats the block you have submitted as a user event, which means that at the end of every perform block it will make sure that all changes are processed and relevant notifications are sent.

every block submitted through the perform(_:) method gets wrapped in an autorelease pool.

performAndWait(_:) 有讨厌的副作用并且没有自动释放池,它会完全阻塞调用线程!您必须调用 processPendingChangessave() 才能使更改生效。

关于ios - 为什么我们在核心数据中使用performWait?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53776340/

相关文章:

ios - 在 SwiftUI 中声明 Binding 属性有什么区别?

ios - 核心数据是一种图数据库吗?

ios - 更改 TextView 高度 - iOS

iOS 应用程序在不使用 iOS 11 API 的情况下遵守 iPhone X 屏幕限制

ios - 无法将类型 'NSNull' 的值转换为 'NSNumber'

ios - 读取 Firebase Auth 抛出错误(Firebase 3.x 和 Swift)

objective-c - 检测Xcode项目开发语言

iPhone 核心数据 - 访问具有许多关系的深层属性

ios - 核心数据迁移——如何将两个实体合二为一

ios - CGRectMake : How To Calculate X and Y For UIPickerView Animation?