Subject: Critical Issue with SwiftData in Xcode 15
Dear Apple Developer Support,
I hope this message finds you well. I am writing to address a significant concern with the SwiftData framework introduced at WWDC 2023.
Background:
In June, during WWDC 2023, Apple unveiled SwiftData, a construct built upon the new Swift macros. This construct overlays a new API on top of Objective-C's Core Data, aiming to simplify and make data persistence more intuitive. The primary focus of SwiftData, as demonstrated in the WWDC code samples and videos, is to support apps that start from a data-empty state (akin to the Notes app) and gradually populate data, potentially integrating with a CloudKit-based backend. When integrated in this manner, predominantly through SwiftUI without background processes, the experience is seamless and indeed a significant improvement. However, there's a limitation: real-time access to the Predicate of a @Query is missing, requiring the query to be recreated.
The Issue:
The challenge arises when attempting to utilize SwiftData for background operations, especially with concurrent threads. SwiftData provides developers with only the mainContext, which is explicitly tied to the @MainActor, restricting its use to the main thread. This becomes problematic when interfacing with a custom API, where data needs to be frequently sent or received from a server. To create background contexts, developers are forced to resort to the ModelActor protocol, which mandates the use of Actors, contexts, and executors to manage these contexts. Ideally, SwiftData should offer an out-of-the-box background context, rather than requiring developers to set it up manually.
Up until beta 6, using the background context to, for instance, send or fetch data from a server, especially during batch loads of over 1,000 records (essential for app initialization), worked flawlessly. However, once the background data load completed, the UI wouldn't refresh automatically, necessitating a restart. From beta 7 onwards, while the data does refresh, the background context ceased to function correctly. Even when encapsulated within a Task and ensuring operations are in the background, accessing the database context occurs on the main thread. This behavior stalls the UI during batch loads and results in a choppy UI experience during data send/receive operations with custom APIs.
From my analysis, it seems that to address the UI refresh issue, some processes were elevated to the main thread. However, this change severely compromises the efficiency of background operations.
Conclusion:
We are now working with the final version of Xcode 15, and such a critical issue in a library as pivotal as SwiftData is concerning. I kindly urge the team to address this matter promptly.
Thank you for your attention to this matter.
Warm regards,
Julio César Fernández