Post

Replies

Boosts

Views

Activity

Swift UI + Core Data in a background thread?
I have a couple of places in my SwiftUI app where I need to fetch a (growing) set of information from CoreData and process it before updating the UI. I am using the MVVM approach for this and so have a number of NSFetchedResultsController instances looking after fetching and updating results. In order to stop blocking the main thread as much I tried shifting the NSFetchedResultsController to perform its work on a background thread instead. This works but only if I disable the -com.apple.CoreData.ConcurrencyDebug 1 argument to ensure I'm not breaching threading rules. I am already ensuring that all CD access is done on the background thread however it appears that when the SwiftUI view accesses a property from the CD object it is doing so on the main thread and so causing a crash. For now I can think of a couple of possible solutions: Ensure that the data fetched by the NSFetchedResultsController can be fetched/processed in a small amount of time to ensure the UI doesn't hang Make "DTO" objects so that data fetched is then inserted into another class instance inside the background thread and have the UI use that. The issue with this approach is then making edits or reacting to updates on the object become a lot more convoluted as you need to manually keep the CD and the DTO objects in-sync.
1
0
1.1k
Jun ’23
Usage of enum when migrating from CoreData
In the "old" world we could define a model property as an integer (e.g. "Integer 64") and then have the actual class representing that model define the property as an enum instead and have getters/setters using methods such as primitiveValue(forKey:) When migrating to use SwiftData I changed the model to be an actual enum type and even though the underlying type of the enum is an integer and therefore supported by the primitive storage it requires me to use Codable on the enum instead and doing so makes it incompatible with the old CoreData model. Does anyone have any ideas or workarounds here or do you feel it is a bug and should be reported? enum FooType: Int64 { case awesome case super } @Model final class Note { var type: FooType // ERROR }
3
0
862
Jun ’23