gpt4 book ai didi

ios - 我是否需要在 DispatchQueue.main.async 中使用 autoreleasepool block

转载 作者:搜寻专家 更新时间:2023-10-31 19:29:00 43 4
gpt4 key购买 nike

在 Xcode 8.2.1 中为 iOS 应用程序使用 swift 3。

我知道在新线程上分派(dispatch)某些处理时我需要一个自动释放池 block 。但是在主线程上分派(dispatch)时需要它吗?

假设我们在主线程上并执行以下操作:

    DispatchQueue.global(qos: .background).async {
autoreleasepool {
//***** do something in the background
} // autoreleasepool

DispatchQueue.main.async {
//***** do something on the main thread when background job is done
//***** does this something need to be enclosed in an autoreleasepool block ?
} // DispatchQueue.main.async

} // DispatchQueue.global

最佳答案

DispatchQueue 有一个“autorelease frequency”属性,它决定每个工作项是否自动被 autorelease{} 包围。它记录在 dispatch/queue.h 而不是 Apple 的文档中,所以我无法链接到它;附上标题中的屏幕截图。

  • DispatchQueue.main 具有自动释放频率 .workitem(这意味着自动释放每个 dispatch_async)
  • DispatchQueue.global 已将其设置为 .never(从不自动自动释放;由您决定)
  • DispatchQueue.init 创建一组到 .inherit。默认情况下,新队列以全局队列为目标,这意味着它是隐式的 .never

documentation screenshot of .never

请注意,此属性仅适用于 .async()。如果执行 .sync(),则必须始终手动管理自动释放情况。

docu screenshot of dispatch_sync

回答您的问题:不需要。在主线程上,您不必使用 autorelease{} 包装您的异步 block 。对于任何其他队列,您需要设置属性或手动包装在 autorelease{} 中。

我建议不要直接发送到 DispatchQueue.global 如果存在自动释放的风险,因为这会泄漏或最终进入永不清空的池中。相反,使用显式自动释放池策略创建您自己的队列。

关于ios - 我是否需要在 DispatchQueue.main.async 中使用 autoreleasepool block ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41793408/

43 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com