While developing apps, I always prioritize using the latest APIs from Apple, as they offer greater convenience compared to the older APIs. However, since these newer APIs lack the rigorous testing of their predecessors, they frequently encounter various issues. Unfortunately, SwiftData falls into this category.
In my recent app, I’ve been working on a SwiftData model with a Relationship. Normally, I save a model with a one-to-many relationship using the following code:
let account = Account(name: "Mert")
account.books.append(Book(name: "The Dawn of Everything"))
modelContext.insert(account)
During testing, I didn’t encounter any problems, and the models were successfully saved into CoreData. However, when I released the beta version through TestFlight and invited some friends to test the app, one of them reported that the app was crashing. She kindly shared the crash report with me.
Upon analyzing the crash report, as is often the case with Apple’s crash reports, it didn’t provide specific details about the issue. Nevertheless, it did point to the relationship:
static _DefaultBackingData.getRelationship<A>(key:managedObject:forType:)
After searching on the internet, I discovered that when using SwiftData, I should save the model and its relationship in a different manner:
let account = Account(name: "Mert")
modelContext.insert(account)
account.books.append(Book(name: "The Dawn of Everything"))
In this corrected version, instead of saving the parent object along with its child object, I first insert the parent object and then append the child object. After the change, the crash was gone.
What’s intriguing about this issue is that it only occurred on the device of my friend who reported the crash, not on the nine other users who tested the app, including myself. This suggests that this might be one of the most significant challenges associated with Apple’s new APIs. When there are issues, they tend to manifest in rare cases, but these issues can have a significant impact on the user experience.