I am dealing with a difficulty with accessing the end result from a carry out block in Core Information when fetching nations from the database in a background context. Here is the code snippet:
actor Repository {
@out there(iOS 15.0, *)
non-public func fetchAllCountries() async -> [MCCountry]? {
let request = getFetchRequest()
let backgroundContext = container.newBackgroundContext()
do {
let end result = attempt await backgroundContext.carry out {
let nations = attempt backgroundContext.fetch(request) as? [MCCountry]
let attributeValue = nations?.first?.countryCode
debugPrint("Nation code (String(describing: attributeValue))") // returns worth
return nations
}
debugPrint("Nation (String(describing: end result))") // crashes right here
return end result
} catch {
debugPrint("error (error)")
return nil
}
}
}
Caller:
Process {
await repository.fetchCountries { lead to
if let end result {
for worth in end result {
debugPrint("Worth is (String(describing: worth.countryCode))") //returns nil
}
}
}
}
The issue is that though I can entry the end result contained in the carry out block, the returned end result from backgroundContext.carry out appears to be inaccessible. When I attempt to entry the end result after the block, I encounter an EXC_BAD_ACCESS error. I anticipated to obtain the end result from the carry out technique and return it instantly within the fetchAllCountries technique.
Am I lacking one thing in my understanding? Should not I anticipate a end result from the carry out block? Can somebody please assist me establish what’s fallacious with the code?
Thanks upfront.