My app is using SwiftData, but I deployed it to the app store with no VersionedSchema applied without thinking about migrating the model. Now I need to migrate the data and I need help from someone who has experience moving from non-versioned to versioned.
Assuming I currently have a version1, version2 schema, it works fine for the initial install situation, but when I migrate to version1, version2 in an app that is listed on the app store, I run into problems.
I don't have any logs to show for it. Thread 1: EXC_BAD_ACCESS (code=2, address=0x16a6578f0) If anyone has had the same experience as above, please respond, thanks!
Let me know what kind of logs you need and I'll add them as a comment.
                    
                  
                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
Created
                    
                      When I logged into my cloudkit console to inspect the database for some debugging work I couldn't access the private database. It keeps saying "failed to access iCloud data, please signi n again". No matter how many times I sign in again, whether with password or passwordless key it keeps saying the same thing. It says that message when I click on Public database, and private and shared databases are below it. I only noticed this a couple of days ago. It's done this in the past, but I eventually got back into the database but I don't know what changed to make it work.
                    
                  
                
                    
                      My app has been in the App Store a few months. In that time I've added a few updates to my SwiftData schema using a MigrationPlan, and things were seemingly going ok. But then I decided to add CloudKit syncing. I needed to modify my models to be compatible. So, I added another migration stage for it, changed the properties as needed (making things optional or adding default values, etc.). In my tests, everything seemed to work smoothly updating from the previous version to the new version with CloudKit. So I released it to my users. But, that's when I started to see the crashes and error reports come in. I think I've narrowed it down to when users update from older versions of the app. I was finally able to reproduce this on my end, and Core Data is throwing an error when loading the ModelContainer saying "CloudKit integration requires that all attributes be optional, or have a default value set." Even though I did this in the latest schema. It’s like it’s trying to load CloudKit before performing the schema migration, and since it can’t, it just fails and won’t load anything. I’m kinda at a loss how to recover from this for these users other than tell them to delete their app and restart, but obviously they’ll lose their data that way. The only other idea I have is to setup some older builds on TestFlight and direct them to update to those first, then update to the newest production version and hope that solves it. Any other ideas? And what can I do to prevent this for future users who maybe reinstall the app from an older version too? There's nothing special about my code for loading the ModelContainer. Just a basic:
let container = try ModelContainer(
    for: Foo.self, Bar.self,
    migrationPlan: SchemaMigration.self,
    configurations: ModelConfiguration(cloudKitDatabase: .automatic)
)
                    
                  
                
                    
                      I'm sorta baffled right now. I am trying to wonder how I might detect a updated SQL Store in an older app.
have a baseline app, and create a SQL-based repository
in an updated app, change the model and verify that you can see the updated model version. Using lightweight migration
re-run the older app (which will inherit the newer SQL repository).
YIKES - no error when creating the NSPersistenStoreCoordinator!
Nothing in the metadata to imply the store is newer than the model:
[_persistentStoreCoordinator metadataForPersistentStore:store]
My question: is there any way to detect this condition?
David
                    
                  
                
                    
                      According to my experiments SwiftData does not work with model attributes of primitive type UInt64. More precisely, it crashes in the getter of a UInt64 attribute invoked on an object fetched from the data store.
With Core Data persistent UInt64 attributes are not a problem. Does anyone know whether SwiftData will ever support UInt64?
                    
                  
                
                    
                      I have an Apple app that uses SwiftData and icloud to sync the App's data across users' devices. Everything is working well. However, I am facing the following issue:
SwiftData does not support public sharing of the object graph with other users via iCloud. How can I overcome this limitation without stopping using SwiftData?
Thanks in advance!
                    
                  
                
                    
                      Hello, I’m upgrading my app from Core Data to SwiftData. Due to my old setup the Core Data store has an explicitly name like „Something.sqlite“, because it was defined via NSPersistentContainer(name: "Something") before switching to SwiftData.
Now my goal is to migrate the Core Data stack to SwiftData, while moving it to an App Group (for Widget support) as well as enable iCloud sync via CloudKit.
Working Migration without App Group & CloudKit
I’ve managed to get my migration running without migrating it to an App Group and CloudKit support like so:
@main
struct MyAppName: App {
    let container: ModelContainer
    
    init() {
        // Legacy placement of the Core Data file.
        let dataUrl = URL.applicationSupportDirectory.appending(path: "Something.sqlite")
        
        do {
            // Create SwiftData container with migration and custom URL pointing to legacy Core Data file
            container = try ModelContainer(
                for: Foo.self, Bar.self,
                migrationPlan: MigrationPlan.self,
                configurations: ModelConfiguration(url: dataUrl))
        } catch {
            fatalError("Failed to initialize model container.")
        }
    }
    
    var body: some Scene {
        WindowGroup {
            ContentView()
        }
        .modelContainer(container)
    }
}
How To Migrate to App Group & CloudKit?
I’ve already tried to use the ModelConfiguration with a name, but it seems to only look for a .store file and thus doesn’t copy over the Core Data contents.
let fullSchema = Schema([Foo.self, Bar.self])
        
let configuration = ModelConfiguration("Something", schema: fullSchema)
Can someone help me how to do this migration or point me into the right direction? I can’t find anything relating this kind of migration …
                    
                  
                
                    
                      I'm currently using Xcode 16 Beta (16A5171c) and I'm getting a crash whenever I attempt to fetch using my ModelContext in my SwiftUI video using the environment I'm getting a crash specifically on iOS 18 simulators.
I've opened up a feedback FB13831520 but it's worth noting that I can run the code I'll explain in detail below on iOS 17+ simulator and devices just fine.
I'm getting the following crash:
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'The specified URI is not a valid Core Data URI: x-coredata:///MyApp/XXXXX-XXXXX-XXXX-XXXX-XXXXXXXXXXXX'
It's almost as if on iOS18 SwiftData is unable to find the file on the simulator to perform CRUD operations.
All I'm doing in my project is simply fetching data using the modelContext.
    func contains(_ model: MyModel, in context: ModelContext) -> Bool {
        let objId = palette.persistentModelID
        let fetchDesc = FetchDescriptor<MyModel>(predicate: #Predicate { $0.persistentModelID == objId })
        let itemCount = try? context.fetchCount(fetchDesc)
        return itemCount != 0
    }
                    
                  
                
                    
                      When trying to run my document-based iPad app using iPadOS 18 beta and Xcode 16 beta, I get an error like the following after opening a document:
Thread 1: Fatal error: Failed to identify a store that can hold instances of SwiftData._KKMDBackingData<MyProject.MyModel> from [:]
In order to help track down what is going wrong, I downloaded the sample app from WWDC23 session "Build an app with SwiftData" found here: https://developer.apple.com/documentation/swiftui/building-a-document-based-app-using-swiftdata
When I try to run the end-state of that sample code, I get a similar error when running the app on my iPad and creating a new deck:
Thread 1: Fatal error: Failed to identify a store that can hold instances of SwiftData._KKMDBackingData<SwiftDataFlashCardSample.Card> from [:]
Given that the sample project is generating the same error as my own project, is this a problem with SwiftData and document-based apps in general? Or is there a change of approach that I should try?
                    
                  
                
                    
                      Since the iOS 18 and Xcode 16, I've been getting some really strange SwiftData errors when passing @Model classes around.
The error I'm seeing is the following:
SwiftData/BackingData.swift:409: Fatal error: This model instance was destroyed by calling ModelContext.reset and is no longer usable. 
PersistentIdentifier(id: SwiftData.PersistentIdentifier.ID(url: x-coredata://34EE9059-A7B5-4484-96A0-D10786AC9FB0/TestApp/p2), implementation: SwiftData.PersistentIdentifierImplementation)
The same issue also happens when I try to retrieve a model from the ModelContext using its PersistentIdentifier and try to do anything with it. I have no idea what could be causing this.
I'm guessing this is just a bug in the iOS 18 Beta, since I couldn't find a single discussion about this on Google, I figured I'd mention it.
if someone has a workaround or something, that would be much appreciated.
                    
                  
                
                    
                      I have encountered an issue that when using a ModelActor to sync data in the background, the app will crash if one of the operations is to remove a PersistentModel from the context.
This is running on the latest beta of Xcode 16 with visionOS 1.2 as target and in Swift 6 language mode.
The code is being executed in a ModelActor.
The error is first thrown by:
#5	0x00000001c3223280 in PersistentModel.getValue<τ_0_0>(forKey:) ()
Thread 1: Fatal error: Context is missing for Optional(SwiftData.PersistentIdentifier(id: SwiftData.PersistentIdentifier.ID(url: x-coredata://97AA86BC-475D-4509-9004-D1182ABA1922/Reminder/p303), implementation: SwiftData.PersistentIdentifierImplementation))
func globalSync() async {
        
        await fetchAndSyncFolders()
        
        let result = await fetchReminders()
        switch result {
        case .success(let ekReminders):
            var localReminders = (try? await fetch(FetchDescriptor<Reminder>())) ?? []
            
            // Handle local reminders with nil ekReminderID by creating new EKReminders for them
            for reminder in localReminders {
                if reminder.ekReminderID == nil {
                    await self.createEkReminder(reminder: reminder)
                }
            }
            
            // Re-fetch local reminders to include newly created EKReminderIDs
            localReminders = (try? await fetch(FetchDescriptor<Reminder>())) ?? []
            
            var localReminderDict = [String: Reminder]()
            for reminder in localReminders {
                if let ekReminderID = reminder.ekReminderID {
                    if let existingReminder = localReminderDict[ekReminderID] {
                        self.delete(model: existingReminder)
                    } else {
                        localReminderDict[ekReminderID] = reminder
                    }
                }
            }
            
            let ekReminderDict = createReminderLookup(byID: ekReminders)
            
            await self.syncReminders(localReminders: Array(localReminderDict.values), localReminderDict: localReminderDict, ekReminderDict: ekReminderDict)
            
            // Merge duplicates
            await self.mergeDuplicates(localReminders: localReminders)
            
            save()
            
        case .failure(let error):
            print("Failed to fetch reminders: \(error.localizedDescription)")
        }
    }
                    
                  
                
                    
                      I have a simple app that uses SwiftUI and SwiftData to maintain a database. The app runs on multiple iPhones and iPads and correctly synchronises across those platforms. So I am correct setting Background Modes and Remote Notifications. I have also correctly setup my Model Configuration and ModelContainer (Otherwise I would expect syncing to fail completely).
The problem arises when I run on a Mac (M1 or M3) either using Mac Designed for iPad or Mac Catalyst. This can be debugging in Xcode or running the built app. Then the app does not reflect changes made in the iPhone or iPad apps unless I follow a specific sequence. Leave the app, (e.g click on a Finder window), then come back to the app (i.e click on the app again). Now the app will show the changes made on the iPhone/iPad.
It looks like the app on the Mac is not processing remote notifications when in the background - it only performs them when the app has just become active. It also looks like the Mac is not performing these sync operations when the app is active. I have tried waiting 30 minutes and still the sync doesn't happen unless I leave the app and come back to it.
I am using the same development CloudKit container in all cases
                    
                  
                
              
                
              
              
                
                Topic:
                  
	
		App & System Services
  	
                
                
                SubTopic:
                  
                    
	
		iCloud & Data
		
  	
                  
                
              
              
              
  
  
    
    
  
  
              
                
                
              
            
          
                    
                      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
                    
                  
                
                    
                      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 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
                    
                  
                
                    
                      [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
                    
                  
                
                    
                      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"