[AltStoreCore] Adds NSManagedObjectContext.performAsync() to wrap iOS 15+ async perform()

Allows us to use Swift Concurrency with Core Data pre-iOS 15.
This commit is contained in:
Riley Testut
2023-04-04 14:06:13 -05:00
committed by Magesh K
parent 779887e582
commit fc99fb32a4
2 changed files with 64 additions and 0 deletions

View File

@@ -0,0 +1,61 @@
//
// AltStore+Async.swift
// AltStoreCore
//
// Created by Riley Testut on 3/23/23.
// Copyright © 2023 Riley Testut. All rights reserved.
//
import UIKit
import CoreData
public extension NSManagedObjectContext
{
// Non-Throwing
func performAsync<T>(_ closure: @escaping () -> T) async -> T
{
let result: T
if #available(iOS 15, *)
{
result = await self.perform(schedule: .immediate) {
closure()
}
}
else
{
result = await withCheckedContinuation { (continuation: CheckedContinuation<T, Never>) in
self.perform {
let result = closure()
continuation.resume(returning: result)
}
}
}
return result
}
// Throwing
func performAsync<T>(_ closure: @escaping () throws -> T) async throws -> T
{
let result: T
if #available(iOS 15, *)
{
result = try await self.perform(schedule: .immediate) {
try closure()
}
}
else
{
result = try await withCheckedThrowingContinuation { (continuation: CheckedContinuation<T, Error>) in
self.perform {
let result = Result { try closure() }
continuation.resume(with: result)
}
}
}
return result
}
}