[AltStoreCore] Backports iOS 15+ NSManagedObjectContext.performAndWait<T>()

Simplifies returning values and throwing errors from managed object contexts.
This commit is contained in:
Riley Testut
2023-05-16 15:15:43 -05:00
parent 5ba5bf995e
commit 6053a075f4
3 changed files with 49 additions and 9 deletions

View File

@@ -0,0 +1,37 @@
//
// NSManagedObjectContext+Conveniences.swift
// AltStore
//
// Created by Riley Testut on 5/16/23.
// Copyright © 2023 Riley Testut. All rights reserved.
//
import CoreData
public extension NSManagedObjectContext
{
// Non-throwing
func performAndWait<T>(_ closure: @escaping () -> T) -> T
{
var result: T!
self.performAndWait {
result = closure()
}
return result
}
// Throwing
func performAndWait<T>(_ closure: @escaping () throws -> T) throws -> T
{
var result: Result<T, Error>!
self.performAndWait {
result = Result { try closure() }
}
let value = try result.get()
return value
}
}

View File

@@ -40,12 +40,12 @@ public extension Managed
// Non-throwing
func perform<T>(_ closure: @escaping (ManagedObject) -> T) -> T
{
var result: T!
let result: T
if let context = self.managedObjectContext
{
context.performAndWait {
result = closure(self.wrappedValue)
result = context.performAndWait {
closure(self.wrappedValue)
}
}
else
@@ -59,21 +59,20 @@ public extension Managed
// Throwing
func perform<T>(_ closure: @escaping (ManagedObject) throws -> T) throws -> T
{
var result: Result<T, Error>!
let result: T
if let context = self.managedObjectContext
{
context.performAndWait {
result = Result { try closure(self.wrappedValue) }
result = try context.performAndWait {
try closure(self.wrappedValue)
}
}
else
{
result = Result { try closure(self.wrappedValue) }
result = try closure(self.wrappedValue)
}
let value = try result.get()
return value
return result
}
}