我正在开发一个仍然支持 iOS 13 并且需要使用 CoreData 获取一些数据的应用程序。
这就是我通常会这样做的方式
context.perform({
let results = try context.fetch(request)
})
现在,随着 Xcode 13 和 async/await 可用于 iOS 13,我得到一个编译器错误
'perform(schedule:_:)' 仅适用于 iOS 15.0 或更高版本
跳转到定义显示 CoreData 中的以下新 API
@available(macOS 12.0, iOS 15.0, tvOS 15.0, watchOS 8.0, *)
extension NSManagedObjectContext {
public func performAndWait<T>(_ block: () throws -> T) rethrows -> T
public func perform<T>(schedule: NSManagedObjectContext.ScheduledTaskType = .immediate, _ block: @escaping () throws -> T) async rethrows -> T
}
当注释掉 Block 中的代码时,它会跳转到 CoreData/NSManagedObjectContext 中的旧 API
/* asynchronously performs the block on the context's queue. Encapsulates an autorelease pool and a call to processPendingChanges */
@available(iOS 5.0, *)
open func perform(_ block: @escaping () -> Void)
为什么编译器会选择新的变体,perform
如何强制它使用旧的非异步版本?
编辑:这是一个演示该问题的最小示例项目:https ://github.com/iv-mexx/CoreDataRepro