I have an app with fairly typical requirements - I need to insert some data (in my case from the network but could be anything) and I want to do it in the background to keep the UI responsive.
I'm using SwiftData.
I've created a ModelActor that does the importing and using the debugger I can confirm that the data is indeed being inserted.
On the UI side, I'm using @Query and a SwiftUI List to display the data but what I am seeing is that @Query is not updating as the data is being inserted. I have to quit and re-launch the app in order for the data to appear, almost like the context running the UI isn't communicating with the context in the ModelActor.
I've included a barebones sample project. To reproduce the issue, tap the 'Background Insert' button. You'll see logs that show items being inserted but the UI is not showing any data.
I've tested on the just released iOS 18b3 seed (22A5307f).
The sample project is here:
https://hanchor.s3.amazonaws.com/misc/SwiftDataBackgroundV2.zip
iCloud & Data
RSS for tagLearn how to integrate your app with iCloud and data frameworks for effective data storage
Selecting any option will automatically load the page
Post
Replies
Boosts
Views
Activity
I've already submitted this as a bug report to Apple, but I am posting here so others can save themselves some troubleshooting. This is submitted as FB14337982 with an attached complete Xcode project to replicate.
In iOS 17 we use a ModelActor to download data which is saved as an Event, and then save it to SwiftData with a relationship to a Location. In iOS 18 22A5307d we are seeing that this code no longer persists the relationship to the Location, but still saves the Event. If we put a breakpoint in that ModelActor we see that the object graph is correct within the ModelActor stack trace at the time we call modelContext.save(). However, after saving, the relationship is missing from the default.store SQLite file, and of course from the app UI.
Here is a toy example showing how inserting an Employee into a Company using a ModelActor gives unexpected results in iOS 18 22A5307d but works as expected in iOS 17.
It appears that no relationships data survives being saved in a ModelActor.ModelContext.
Also note there seems to be a return of the old bug that saving this data in the ModelActor does not update the @Query in the UI in iOS 18 but does so in iOS 17.
Models
@Model
final class Employee {
var uuid: UUID = UUID()
@Relationship(deleteRule: .nullify) public var company: Company?
/// For a concise display
@Transient var name: String {
self.uuid.uuidString.components(separatedBy: "-").first ?? "NIL"
}
init(company: Company?) {
self.company = company
}
}
@Model
final class Company {
var uuid: UUID = UUID()
@Relationship(deleteRule: .cascade, inverse: \Employee.company)
public var employees: [Employee]? = []
/// For a concise display
@Transient var name: String {
self.uuid.uuidString.components(separatedBy: "-").first ?? "NIL"
}
init() { }
}
ModelActor
import OSLog
private let logger = Logger(subsystem: Bundle.main.bundleIdentifier!, category: "SimpleModelActor")
@ModelActor
final actor SimpleModelActor {
func addEmployeeTo(CompanyWithID companyID: PersistentIdentifier?) {
guard let companyID,
let company: Company = self[companyID, as: Company.self] else {
logger.error("Could not get a company")
return
}
let newEmployee = Employee(company: company)
modelContext.insert(newEmployee)
logger.notice("Created employee \(newEmployee.name) in Company \(newEmployee.company?.name ?? "NIL")")
try! modelContext.save()
}
}
ContentView
import OSLog
private let logger = Logger(subsystem: Bundle.main.bundleIdentifier!, category: "View")
struct ContentView: View {
@Environment(\.modelContext) private var modelContext
@Query private var companies: [Company]
@Query private var employees: [Employee]
@State private var simpleModelActor: SimpleModelActor!
var body: some View {
ScrollView {
LazyVStack {
DisclosureGroup("Instructions") {
Text("""
Instructions:
1. In iOS 17, tap Add in View. Observe that an employee is added with Company matching the shown company name.
2. In iOS 18 beta (22A5307d), tap Add in ModelActor. Note that the View does not update (bug 1). Note in the XCode console that an Employee was created with a relationship to a Company.
3. Open the default.store SQLite file and observe that the created Employee does not have a Company relationship (bug 2). The relationship was not saved.
4. Tap Add in View. The same code is now executed in a Button closure. Note in the XCode console again that an Employee was created with a relationship to a Company. The View now updates showing both the previously created Employee with NIL company, and the View-created employee with the expected company.
""")
.font(.footnote)
}
.padding()
Section("**Companies**") {
ForEach(companies) { company in
Text(company.name)
}
}
.padding(.bottom)
Section("**Employees**") {
ForEach(employees) { employee in
Text("Employee \(employee.name) in company \(employee.company?.name ?? "NIL")")
}
}
Button("Add in View") {
let newEmployee = Employee(company: companies.first)
modelContext.insert(newEmployee)
logger.notice("Created employee \(newEmployee.name) in Company \(newEmployee.company?.name ?? "NIL")")
try! modelContext.save()
}
.buttonStyle(.bordered)
Button("Add in ModelActor") {
Task {
await simpleModelActor.addEmployeeTo(CompanyWithID: companies.first?.persistentModelID)
}
}
.buttonStyle(.bordered)
}
}
.onAppear {
simpleModelActor = SimpleModelActor(modelContainer: modelContext.container)
if companies.isEmpty {
let newCompany = Company()
modelContext.insert(newCompany)
try! modelContext.save()
}
}
}
}
Hi!
I'm using CoreData + CloudKit. It works well both on macOS and iOS, however, I can't make it work with extensions (share, action, keyboard).
I get Invalid bundle ID for container error:
<CKSchedulerActivity: 0x3029f4d20; identifier=com.apple.coredata.cloudkit.activity.export.A65D5B7A-18AA-400A-B25F-F042E46646F6, priority=2, container=iCloud.com.org.app.dev:Sandbox, relatedApplications=(
"com.org.App.dev.App-Keyboard"
), xpcActivityCriteriaOverrides={
ActivityGroupName = "com.apple.coredata.cloudkit.App Keyboard.A65D5B7A-18AA-400A-B25F-F042E46646F6";
Delay = 0;
Priority = Utility;
}>
error: CoreData+CloudKit: -[NSCloudKitMirroringDelegate _recoverFromPartialError:forStore:inMonitor:](2812): <NSCloudKitMirroringDelegate: 0x303fd82d0>: Error recovery failed because the following fatal errors were found: {
"<CKRecordZoneID: 0x300ef9bc0; zoneName=com.apple.coredata.cloudkit.zone, ownerName=__defaultOwner__>" = "<CKError 0x300efa5e0: \"Permission Failure\" (10/2007); server message = \"Invalid bundle ID for container\"; op = xxxxxxx; uuid = zzzzz-xxxxx; container ID = \"iCloud.com.org.app.dev\">";
}
I checked everything 10x: profiles, bundle ids, entitlements, etc. I even removed all local provisioning profiles and recreated them, I also tried setting different CloudKit container, but nothing helps. I tested it on a real device.
My setup:
main app bundle id: com.org.App.dev
keyboard bundle id: com.org.App.dev.App-Keyboard
action extension bundle id: com.org.App.dev.Action-Extension
CloudKit container id: iCloud.com.org.app.dev
I keep the CoreData database in the app group container, but I also tried locally and it doesn't really matter.
This is how I setup my CoreData:
self.persistentContainer = NSPersistentCloudKitContainer(name: "AppCoreModel")
persistentContainer.persistentStoreDescriptions = [createCloudStoreDescription()]
persistentContainer.loadPersistentStores { [self] _, error in
if let error {
logError("Could not load Core Data store \(error)")
} else {
persistentContainer.viewContext.automaticallyMergesChangesFromParent = true
persistentContainer.viewContext.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy
logDebug(persistentContainer.persistentStoreDescriptions.first?.url?.absoluteString ?? "")
logDebug("Core Data store loaded")
}
}
private func createCloudStoreDescription() -> NSPersistentStoreDescription {
let cloudStoreOptions = NSPersistentCloudKitContainerOptions(
containerIdentifier: "iCloud.com.org.app.dev"
)
cloudStoreOptions.databaseScope = .private
let documentsUrl = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: AppConstants.appGroupId)!
let cloudStoreDescription = NSPersistentStoreDescription(
url: documentsUrl.appendingPathComponent("cloud-database.sqlite")
)
cloudStoreDescription.type = NSSQLiteStoreType
cloudStoreDescription.cloudKitContainerOptions = cloudStoreOptions
cloudStoreDescription.setOption(true as NSNumber, forKey: NSPersistentHistoryTrackingKey)
cloudStoreDescription.setOption(true as NSNumber, forKey: NSPersistentStoreRemoteChangeNotificationPostOptionKey)
return cloudStoreDescription
}
Any help would be highly appreciated. It seems like iOS bug, because everything seems to be configured properly. I even checked app identifiers if containers are properly assigned.
Similar issue when using CloudKit directly (unresolved):
https://developer.apple.com/forums/thread/665280
Topic:
App & System Services
SubTopic:
iCloud & Data
Tags:
CloudKit
Cloud and Local Storage
Core Data
Hi everyone,
Have anybody faced with Core Data issues, trying to migrate the project to Xcode16 beta 4?
We are using transformableAttributeType in some entities, with attributeValueClassName = "[String]" and valueTransformerName = "NSSecureUnarchiveFromData". It is working just fine for years, but now I am trying to run the project from Xcode16 and have 2 issues:
in Xcode logs I see warning and error:
CoreData: fault: Declared Objective-C type "[String]" for attribute named alertBarChannels is not valid
CoreData: Declared Objective-C type "[String]" for attribute named alertBarChannels is not valid
periodically the app crashes when we are assigning value to this attribute, with error:
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFConstantString characterAtIndex:]: Range or index out of bounds'
Once again, in Xcode 15 it works fine, and it was working for years.
Cannot find any information about what was changed in the framework...
Thank you in advance for any information, which could clarify what is going on.
Recently I've been working on a demo project called iLibrary. The main goal was to learn more about CloudKit and SwiftData. After a while I noticed that there were some hangs/freezes when running the app in debug mode.
I first tried this with Xcode 15.4 and iOS 17.5. Here the hang only appears at the beginning, but only for a few seconds. But when I exit debug mode, there are no more hangs.
With Xcode 16 beta 4 and iOS 18 it looks completely different. In this case, the hangs and freezes are always present, whether in debug mode or not. And it's not just at the beginning, it's throughout the app. I'm aware that this is still a beta, but I still find this weird. And when I profile this I see that the main thread gets quite overloaded. Interestingly, my app doesn't have that many operations going on. So I guess something with the sync of SwiftData or my CloudKitManger where I fetch some records from the public database is not running fine.
Lastly, I wanted to delete the iCloud app data. So I went to Settings and tried to delete it, but it didn't work. Is this normal?
Does anyone have any idea what this could be? Or has anyone encountered this problem as well? I'd appreciate any support.
My project: https://github.com/romanindermuehle/iLibrary
Posting here to see if folks have workarounds or if I have a misunderstanding of SwiftData supported types.
In adopting SwiftData, I have swiftData properties of collection type (Array or Set - both have this issue). E.g:
@Model
final class Item {
var timestamp: Date
var strings = ["aa", "bb"]
var display: String {
strings.joined(separator: " ")
}
init(timestamp: Date) {
self.timestamp = timestamp
}
}
So far in development I haven't had issues on iOS 17, but on the iOS 18 betas 4-5 the app logs show the following error:
"fault: Could not materialize Objective-C class named "Array" from declared attribute value type "Array<String>" of attribute named strings"
It happens immediately in my app when creating an object with a collection attribute.
In a minimal test example, the error log appears only after a few minutes and doesn't seem to affect the template app's basic functionality.
Anyone else running into this?
Was filed as FB14397250
Hi,
I'm struggling with SwiftData and the components for migration and could really use some guidance. My specific questions are
Is it possible to go from an unversioned schema to a versioned schema?
Do all @Model classes need to be converted?
Is there one VersionedSchema for the entire app that handles all models or one VersionedSchema per model?
What is the relationship, if any, between the models given to ModelContainer in a [Schema] and the models in the VersionedSchema in a [any PersistentModel.Type]
I have an app in the AppStore. I use SwiftData and have four @Models defined. I was not aware of VersionedSchema when I started, so they are unversioned. I want to update the model and am trying to convert to a VersionedSchema. I've tried various things and can't even get into the migration plan yet. All posts and tutorials that I've come across only deal with one Model, and create a VersionedSchema for that model.
I've tried to switch the one Model I want to update, as well as switching them all. Of course I get different errors depending on what configuration I try.
It seems like I should have one VersionedSchema for the app since there is the static var models: [any PersistentModel.Type] property. Yet the tutorials I've seen create a TypeNameSchemaV1 to go with the @Model TypeName.
Which is correct? An AppNameSchemaV1 which defines four models, or four TypeNameSchemaV1?
Any help will be much appreciated
Whilst all current answers to this question indicate the depreciation of CKModifyBadgeOperation, all of them had advised up until 2022 that it could still be used due to Apple not having a replacement Api. Upon running the following code:
badgeReset.modifyBadgeCompletionBlock = { (error) -> Void in
if error != nil {
print("Error resetting badge: \(error!)")
}
}
CKContainer.default().add(badgeReset)
When run I receive the following error:
Error resetting badge: <CKError 0x3001ddf50: "Invalid Arguments" (12/1017); "CKModifyBadgeOperation is no longer supported">
And from testing following this, the badge count incrementation issue continues, indicating that this has been completely invalidated and cannot be used at all.
Even with UNUserNotificationCenter.current().setBadgeCount(0) this only clears the badge count temporarily.
I'm aware of the proposed "workaround" of creating an extension that manually keeps track of notification count & sets the badge accordingly when a notification is received. However I'm trying to ascertain if as of this current point in time there is now no way whatsoever to clear the badge count on the Cloudkit sever level?
[Submitted as FB14860454, but posting here since I rarely get responses in Feedback Assistant]
In a simple SwiftData app that adds items to a list, memory usage drastically increases as items are added. After a few hundred items, the UI lags and becomes unusable.
In comparison, a similar app built with CoreData shows only a slight memory increase in the same scenario and does NOT lag, even past 1,000 items.
In the SwiftData version, as each batch is added, memory spikes the same amount…or even increases! In the CoreData version, the increase with each batch gets smaller and smaller, so the memory curve levels off.
My Question
Are there any ways to improve the performance of adding items in SwiftData, or is it just not ready for prime time?
Example Projects
Here are the test projects on GitHub if you want to check it out yourself:
PerfSwiftData
PerfCoreData
Hi,
when using CKSynEgine it is the responsibility of the app to implement CKSyncEngineDelegate. One of the methods of CKSyncEngineDelegate is nextFetchChangesOptions. The implementation of this method should return a batch of CKRecords so that CKSyncEngine can do the syncing whenever it thinks it should sync. A simple implementation might look like this:
func nextRecordZoneChangeBatch(
_ context: CKSyncEngine.SendChangesContext,
syncEngine: CKSyncEngine) async -> CKSyncEngine.RecordZoneChangeBatch?{
await CKSyncEngine.RecordZoneChangeBatch(pendingChanges: syncEngine.state.pendingRecordZoneChanges) { recordID in
// here we should fetch to local representation of the value and map it to a CKRecord
}
}
The problem I am having is as follows:
If the CKRecords I am returning in a batch have dependencies between each other (using CKRecord.Reference or the parent property) but are not part of the same batch, the operation could fail. And as far as I understand, there is no way to prevent this situation because:
A:
The batch I can return is limited in size. If the number of CKRecords is too large, I have to split them into multiple batches.
B:
Splitting them is arbitrary, since I only have the recordID at this point, and there is no way to know about the dependencies between them just by looking at the recordID.
So basically my question is: how should the implementation of nextRecordZoneChangeBatch look like to handle dependencies between CKRecords?
Topic:
App & System Services
SubTopic:
iCloud & Data
I'm using SwiftData with an @Model and am also using an @ModelActor. I've fixed all concurrency issues and have migrated to Swift 6. I am getting a console error that I do not understand how to clear. I get this error in Swift 6 and Swift 5. I do not experience any issue with the app. It seems to be working well. But I want to try to get all issues taken care of. I am using the latest Xcode beta.
error: the replacement path doesn't exist:
"/var/folders/1q/6jw9d6mn0gx1znh1n19z2v9r0000gp/T/swift-generated-sources/@_swiftmacro_17MyAppName14MyModelC4type18_PersistedPr> opertyfMa.swift"
After installing iOS 18.1 and iPados 18.1 we get a consuste failure when trying to add to our one to many data model. This was working well until we installed 18.1
when trying to add a entry to the many relationship we get this error
Illegal attempt to map a relationship containing temporary objects to its identifiers.
Topic:
App & System Services
SubTopic:
iCloud & Data
I’m working on a project where I’m using CKSyncEngine to sync different types of SwiftData models, specifically User and Organization, to CloudKit. Here’s how I schedule these models to be synced:
For the User model:
let pendingSaves: [CKSyncEngine.PendingRecordZoneChange] = [.saveRecord(user.recordID)]
syncEngine.state.add(pendingRecordZoneChanges: pendingSaves)
For the Organization model:
let pendingSaves: [CKSyncEngine.PendingRecordZoneChange] = [.saveRecord(organization.recordID)]
syncEngine.state.add(pendingRecordZoneChanges: pendingSaves)
The problem arises in my CKSyncEngineDelegate's nextRecordZoneChangeBatch method where from CKRecord.ID alone I need to create the actual CKRecord that will be synced to CloudKit. This recordID alone doesn’t provide enough information to determine 1) in which local model table I need to fetch actual data to build whole CKRecord; and 2) what to put in CKRecord.recordType - whether it’s a User or an Organization.
Question:
What is the best practice for passing or determining the model type (e.g., User or Organization) in nextRecordZoneChangeBatch? How should I handle this in a way that effectively differentiates between the different model types being synced?
Any advice or examples would be greatly appreciated!
Few ideas:
embed the Model type in RecordID.recordName string, but this makes my recordNames longer (like resource_29af3932).
fetch data by recordID in all local persistent storage, but this seems slow and there is constraint that User and Organization IDs should never be the same.
introduce lookup table where from CKRecordID I can look up model type.
Somehow extend CKRecordID to add model type field?
I'm using SwiftData to persist my items in storage. I used .modelContext to pass in my shared context, and on iOS 18 (both on a physical device and a simulator), I discovered a bug where SwiftData doesn't automatically save my data. For example, I could add a new item, go to the next screen, change something that reloads a previous screen, and SwiftData just forgets the item that I added. Please find the fully working code attached.
While writing this post, I realized that if I use .modelContainer instead of .modelContext, the issue is solved. So I have two questions:
It seems like .modelContainer is the go-to option when working with SwiftData, but why did an issue occur when I used .modelContext and passed in a shared container? When should we use .modelContext over .modelContainer?
What was the bug? It's working fine in iOS 17, but not in iOS 18. Or is this expected?
Here's the fully working code so you can copy and paste:
import SwiftUI
import SwiftData
typealias NamedColor = (color: Color, name: String)
extension Color {
init(r: Double, g: Double, b: Double) {
self.init(red: r/255, green: g/255, blue: b/255)
}
static let namedColors: [NamedColor] = [
(.blue, "Blue"),
(.red, "Red"),
(.green, "Green"),
(.orange, "Orange"),
(.yellow, "Yellow"),
(.pink, "Pink"),
(.purple, "Purple"),
(.teal, "Teal"),
(.indigo, "Indigo"),
(.brown, "Brown"),
(.cyan, "Cyan"),
(.gray, "Gray")
]
static func name(for color: Color) -> String {
return namedColors.first(where: { $0.color == color })?.name ?? "Blue"
}
static func color(for name: String) -> Color {
return namedColors.first(where: { $0.name == name })?.color ?? .blue
}
}
@main
struct SwiftDataTestApp: App {
var sharedModelContainer: ModelContainer = {
let schema = Schema([
Item.self,
])
let modelConfiguration = ModelConfiguration(schema: schema, isStoredInMemoryOnly: false)
do {
return try ModelContainer(for: schema, configurations: [modelConfiguration])
} catch {
fatalError("Could not create ModelContainer: \(error)")
}
}()
@AppStorage("accentColor") private var accentColorName: String = "Blue"
var body: some Scene {
WindowGroup {
NavigationStack {
HomeView()
}
.tint(Color.color(for: accentColorName))
}
.modelContainer(sharedModelContainer) // This works
// .modelContext(ModelContext(sharedModelContainer)) // This doesn't work
}
}
@Model
final class Item {
var timestamp: Date
init(timestamp: Date) {
self.timestamp = timestamp
}
}
struct HomeView: View {
@State private var showSettings = false
@Environment(\.modelContext) var modelContext
@AppStorage("accentColor") private var accentColorName: String = "Blue"
@Query private var items: [Item]
var body: some View {
List {
ForEach(items) { item in
NavigationLink {
Text("Item at \(item.timestamp, format: Date.FormatStyle(date: .numeric, time: .standard))")
} label: {
Text(item.timestamp, format: Date.FormatStyle(date: .numeric, time: .standard))
}
}
Button {
withAnimation {
let newItem = Item(timestamp: Date())
modelContext.insert(newItem)
}
} label: {
Image(systemName: "plus")
.frame(maxWidth: .infinity)
.frame(maxHeight: .infinity)
}
}
.navigationTitle("Habits")
.toolbar {
ToolbarItem(placement: .navigationBarTrailing) {
Button(action: { showSettings = true }) {
Label("", systemImage: "gearshape.fill")
}
}
}
.navigationDestination(isPresented: $showSettings) {
colorPickerView
}
}
private var colorPickerView: some View {
Form {
Section(header: Text("Accent Color")) {
Picker("Accent Color", selection: $accentColorName) {
ForEach(Color.namedColors, id: \.name) { namedColor in
Text(namedColor.name)
.tag(namedColor.name)
.foregroundColor(namedColor.color)
}
}
.pickerStyle(.wheel)
}
}
.navigationTitle("Settings")
}
}
I have been using the basic NSPersistentContainer with 100k+ records for a while now with no issues. The database size can fluctuate a bit but on average it takes up about 22mb on device.
When I switch the container to NSPersistentCloudKitContainer, I see a massive increase in size to ~150mb initially. As the sync engine uploads records to iCloud it has ballooned to over 600mb on device. On top of that, the user's iCloud usage in settings reports that it takes up 1.7gb in the cloud.
I understand new tables are added and history tracking is enabled but the size increase seems a bit drastic. I'm not sure how we got from 22mb to 1.7gb with the exact same data.
A few other things that are important to note:
I import all the 100k+ records at once when testing the different containers. At the time of the initial import there is only 1 relation (an import group record) that all the records are attached to.
I save the background context only once after all the records and the import group have been made and added to the context.
After the initial import, some of these records may have a few new relations added to them over time. I suppose this could be causing some of the size increase, but its only about 20,000 records that are updated.
None of the records include files/ large binary data.
Most of the attributes are encrypted.
I'm syncing to the dev iCloud environment.
When I do make a change to a single attribute in a record, CloudKit reports that every attribute has been modified (not sure if this is normal or not )
Also, When syncing to a new device, the sync can take hours - days. I'm guessing it's having to sync both the new records and the changes, but it exponentially gets slower as more records are downloaded. The console will show syncing activity, but new records are being added at a slower rate as more records are added. After about 50k records, it grinds to a halt and while the console still shows sync activity, only about 100 records are added every hour.
All this to say i'm very confused where these issues are coming from. I'm sure its a combination of how i've setup my code and the vast record count, record history, etc.
If anyone has any ideas it would be much appreciated.
Is it ok to have latency about 4 sec? The amount of downloaded data is less than 1 MB. Maybe I need to setup an index for every field requested?
Hi,
I understand how to make one to many relationship in SwiftData and how to show the child records, like all cities of a country. But how to navigate and show the parent record from a child record, Like I want to show a country of a city ?
like country.cities show all cities of a country, will cities.country work to show the country ? like cities.country.name ?
Kind Regards
I'm still getting started with SwiftData and having trouble understanding how to persist a model with a relationship in a container. I've tried to distill the example below to be pretty simple.
Here are some example model definitions. I would like to be able to define a n Item. That Item can have SubItems related to it in a one-to-many fashion. Each SubItem is required to be attached to a parent Item.
final class Item {
var name: String
var subitems: [Item]?
init(
name: String,
subitems: [SubItem]? = nil
) {
self.name = name
}
}
@Model
final class SubItem {
var name: String
init(name: String) {
self.name = name
}
}
In my app I am then defining a preview container with some pre-saved data already.
Item(
name: "item1",
subitems: [
SubItem(name: "subItemA"),
SubItem(name: "subItemB")
]
),
Item(
name: "item2",
subitems: [
SubItem(name: "subItemC"),
SubItem(name: "subItemD")
]
)
]
@MainActor
let PreviewContainer: ModelContainer = {
do {
let schema = Schema([
Item.self,
SubItem.self,
])
let container = try ModelContainer(
for: schema, configurations: ModelConfiguration(isStoredInMemoryOnly: true)
)
for item in PreviewItems {
container.mainContext.insert(item)
for subItem in item.subitems! {
container.mainContext.insert(subItem)
}
}
return container
} catch {
fatalError("Failed to create container")
}
}()
My app is then defined as follows...
struct SwiftDataTestApp: App {
var body: some Scene {
WindowGroup {
ContentView()
}
.modelContainer(PreviewContainer)
}
}
struct ContentView: View {
@Environment(\.modelContext) private var modelContext
@Query private var items: [Item]
var body: some View {
HStack {
VStack {
Text(items[0].name)
Text(String(items[0].subitems!.count))
// Text(items[0].subitems![0].name)
// Text(items[0].subitems![1].name)
}
Spacer()
VStack {
Text(items[1].name)
Text(String(items[1].subitems!.count))
// Text(items[0].subitems![0].name)
// Text(items[0].subitems![1].name)
}
}
.padding(100)
}
}
#Preview {
ContentView()
.modelContainer(PreviewContainer)
}
The preview loads without an issue, but if I uncomment the lines that access the SubItems it crashes. In the preview I can also see that each Item has 0 SubItems related to it. For some reason, the model container is not actually storing the `SubItem even though they are defined in PreviewItems.
Some things I've tried
Explicitly adding the relationship
Adding a Item property in SubItem to link back to it's parent
In the PreviewContainer definition, manually insert the SubItems as well as the parent Items
Any help is appreciated, thanks
I'm still getting this error (SwiftData/ModelContext.swift:3253: Fatal error: Failed to identify a store that can hold instances of SwiftData._KKMDBackingData<Presents_2024.Item> from [:]) in Xcode 16.1 Beta (16B5001e).
The app works for a limited amount of time and then crashes with this error. It looks like the SwiftData model isn't being created properly and when a context is saved it crashes.
Can you tell me if this error will be fixed in the next beta?
Topic:
App & System Services
SubTopic:
iCloud & Data
Tags:
Xcode
Xcode Sanitizers and Runtime Issues
Core Data
SwiftData
In iOS 18 RC, and the iOS 18 simulator shipped with Xcode 16.0 RC, there is a regression where ModelContexts on the same ModelContainer do not sync changes. A minimal example is below, but briefly: create an object in context1. Retrieve and update that object in context2, then save context2. The changes cannot be found in context1 in iOS 18 RC, but can in iOS 17 and earlier betas of iOS 18.
I've submitted this as FB15092827 but am posting here for visibility to others. I'm going to have to scramble to see if I can mitigate this in our impacted app before iOS 18 launches. It's affecting us when doing background inserts in a ModelActor to populate our app UI, but you can see below the effects are seen even on the same thread in a very simple two-context example.
@Test("updates sync between contexts") func crossContextSync() async throws {
// overview:
// create an employee in context 1
// update the employee in context 2
// check that the update is available in context 1
let context1 = ModelContext(demoAppContainer)
let context2 = ModelContext(demoAppContainer)
// create an employee in context 1
let newEmployee = Employee(salary: 0)
context1.insert(newEmployee)
try context1.save()
#expect(newEmployee.salary == 0, "Created with salary 0")
// update the employee in context 2
let employeeID = newEmployee.uuid
let predicate: Predicate<Employee> = #Predicate<Employee> { employee in
employee.uuid == employeeID
}
let fetchedEmployee = try #require(try? context2.fetch(FetchDescriptor<Employee>(predicate: predicate)).first)
#expect(fetchedEmployee.uuid == newEmployee.uuid, "We got the correct employee in the new context")
let updatedSalary = 1
fetchedEmployee.salary = updatedSalary
try context2.save()
// FAILURE IS HERE. This passes in earlier iOS betas and in iOS 17.X
#expect(newEmployee.salary == updatedSalary, "Salary was update in context 1")
// Create a new modelContext on the same container, since the container does have the changes in it.
// By creating this new context we can get updated data and the test below passes in all iOS versions tested. This may be a mitigation path but creating new contexts any time you need to access data is painful.
let context3 = ModelContext(demoAppContainer)
let fetchedEmployeeIn3 = try #require(try? context3.fetch(FetchDescriptor<Employee>(predicate: predicate)).first)
#expect(fetchedEmployeeIn3.uuid == newEmployee.uuid, "We got the correct employee in the new context3")
#expect(fetchedEmployeeIn3.salary == updatedSalary, "Salary was update in context 1")
}
Code below if you want to build a working example, but the test above is very simple
let demoAppContainer = try! ModelContainer(for: Employee.self)
@main
struct ModelContextsNotSyncedToContainerApp: App {
init() {
}
var body: some Scene {
WindowGroup {
ContentView()
.modelContainer(demoAppContainer)
}
}
}
@Model
final class Employee {
var uuid: UUID = UUID()
var salary: Int
init(salary: Int = 0) {
self.salary = salary
}
}