Created
September 10, 2021 07:58
-
-
Save ninjitaru/571be9d8c198eb677c13f52a25a4115e to your computer and use it in GitHub Desktop.
NSAsynchronousFetchRequest test
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
let asyncRequest = NSAsynchronousFetchRequest(fetchRequest: request) { fetchResult in | |
// this may or may not right in the same thread as the context thread | |
// except when the context is main thread, this will always run in main thread | |
// TODO: can i access NSManagedObject safely if this is not the same thread? | |
print("ttt: blk thread: \(Thread.current)") | |
Thread.sleep(forTimeInterval: 100) | |
guard let dataResult = fetchResult.finalResult else { | |
return | |
} | |
print(dataResult.count) | |
let summaries = aggregateSummary(result: dataResult, currencies: accountCurrencies) | |
print("ttt: completed") | |
} | |
context.perform { | |
print("ttt: perform thread: \(Thread.current)") | |
do { | |
// cannot just use asyncRequest.execute() due to this is iOS 10 and up | |
let result = try context.fetch(currencyRequest) | |
for data in result { | |
if let id = data["id"] as? String, | |
let currency = data["currency"] as? String { | |
accountCurrencies[id] = currency | |
} | |
} | |
// will finish right away | |
try context.execute(asyncRequest) | |
} catch let error { | |
Crashlytics.crashlytics().record(error: CoreDataError.fetchError(#function, error)) | |
} | |
print("ttt perform ended") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment