I'm experiencing a crash during a lightweight Core Data migration when a widget that accesses the same database is installed. The migration fails with the following error:
CoreData: error: addPersistentStoreWithType:configuration:URL:options:error: returned error NSCocoaErrorDomain (134100)
error: userInfo:
CoreData: error: userInfo:
error: metadata : {
NSPersistenceFrameworkVersion = 1414;
NSStoreModelVersionChecksumKey = "dY78fBnnOm7gYtb+QT14GVGuEmVlvFSYrb9lWAOMCTs=";
NSStoreModelVersionHashes = {
Entity1 = { ... };
Entity2 = { ... };
Entity3 = { ... };
Entity4 = { ... };
Entity5 = { ... };
};
NSStoreModelVersionHashesDigest = "aOalpc6zSzr/VpduXuWLT8MLQFxSY4kHlBo/nuX0TVQ/EZ+MJ8ye76KYeSfmZStM38VkyeyiIPf4XHQTMZiH5g==";
NSStoreModelVersionHashesVersion = 3;
NSStoreModelVersionIdentifiers = (
""
);
NSStoreType = SQLite;
NSStoreUUID = "9AAA7AB7-18D4-4DE4-9B54-893D08FA7FC4";
"_NSAutoVacuumLevel" = 2;
}
The issue occurs only when the widget is installed. If I remove the widget’s access to the Core Data store, the migration completes successfully. The crash happens only once—after the app is restarted, everything works fine.
This occurs even though I'm using lightweight migration, which should not require manual intervention. My suspicion is that simultaneous access to the Core Data store by both the main app and the widget during migration might be causing the issue.
Has anyone encountered a similar issue? Is there a recommended way to ensure safe migration while still allowing the widget to access Core Data?
Any insights or recommendations would be greatly appreciated.
iCloud & Data
RSS for tagLearn how to integrate your app with iCloud and data frameworks for effective data storage
Post
Replies
Boosts
Views
Activity
Exact same app works fine in debug builds, but on release builds I see this stacktrace indicating that assert() was hit.
Incident Identifier: ***
Distributor ID: com.apple.TestFlight
Hardware Model: iPhone14,3
Process: AuditOS [67847]
Path: /private/var/containers/Bundle/Application/***
Identifier: ***
Version: 1.0 (15)
AppStoreTools: 16C5031b
AppVariant: 1:iPhone14,3:18
Beta: YES
Code Type: ARM-64 (Native)
Role: Foreground
Parent Process: launchd [1]
Coalition: ***
Date/Time: 2025-02-11 12:37:54.7801 -0600
Launch Time: 2025-02-11 12:37:33.1737 -0600
OS Version: iPhone OS 18.3 (22D63)
Release Type: User
Baseband Version: 4.20.03
Report Version: 104
Exception Type: EXC_BREAKPOINT (SIGTRAP)
Exception Codes: 0x0000000000000001, 0x000000019d388e2c
Termination Reason: SIGNAL 5 Trace/BPT trap: 5
Terminating Process: exc handler [67847]
Triggered by Thread: 0
Thread 0 Crashed:
0 libswiftCore.dylib 0x000000019d388e2c _assertionFailure(_:_:file:line:flags:) + 264 (AssertCommon.swift:147)
1 SwiftData 0x0000000261842e04 Schema.KeyPathCache.validateAndCache(keypath:on:) + 2628 (Schema.swift:0)
2 SwiftData 0x000000026178cac4 static PersistentModel.keyPathToString(keypath:) + 360 (DataUtilities.swift:36)
3 SwiftData 0x000000026184c9e4 static PersistentModel.fetchDescriptorKeyPathString(for:) + 36 (FetchDescriptor.swift:51)
4 SwiftData 0x00000002617b9770 closure #1 in PredicateExpressions.KeyPath.convert(state:) + 172 (FetchDescriptor.swift:458)
5 SwiftData 0x00000002617b7f48 PredicateExpressions.KeyPath.convert(state:) + 352 (FetchDescriptor.swift:438)
6 SwiftData 0x00000002617bb7ec protocol witness for ConvertibleExpression.convert(state:) in conformance PredicateExpressions.KeyPath<A, B> + 16 (<compiler-generated>:0)
7 SwiftData 0x00000002617baaa0 PredicateExpression.convertToExpressionOrPredicate(state:) + 716 (FetchDescriptor.swift:219)
8 SwiftData 0x00000002617ba6dc PredicateExpression.convertToExpression(state:) + 32 (FetchDescriptor.swift:237)
9 SwiftData 0x00000002617b7cfc PredicateExpressions.Equal.convert(state:) + 328 (:-1)
10 SwiftData 0x00000002617bba08 protocol witness for ConvertibleExpression.convert(state:) in conformance PredicateExpressions.Equal<A, B> + 64 (<compiler-generated>:0)
11 SwiftData 0x00000002617baaa0 PredicateExpression.convertToExpressionOrPredicate(state:) + 716 (FetchDescriptor.swift:219)
12 SwiftData 0x00000002617b7abc PredicateExpression.convertToPredicate(state:) + 28 (FetchDescriptor.swift:244)
13 SwiftData 0x00000002617b7190 nsFetchRequest<A>(for:in:) + 1204 (FetchDescriptor.swift:64)
14 SwiftData 0x0000000261783358 DefaultStore.fetch<A>(_:) + 292 (DefaultStore.swift:496)
15 SwiftData 0x000000026178322c protocol witness for DataStore.fetch<A>(_:) in conformance DefaultStore + 16 (<compiler-generated>:0)
16 SwiftData 0x00000002617847fc asDataStore #1 <A><A1>(_:) in closure #1 in ModelContext.fetch<A>(_:) + 3152 (ModelContext.swift:2590)
17 SwiftData 0x00000002617a74d8 partial apply for closure #1 in ModelContext.fetch<A>(_:) + 100 (<compiler-generated>:0)
18 SwiftData 0x00000002617a7438 closure #1 in ModelContext.enumerateFetchableStores<A>(_:_:) + 208 (ModelContext.swift:2527)
19 SwiftData 0x00000002617a731c specialized ModelContext.enumerateFetchableStores<A>(_:_:) + 200 (ModelContext.swift:2522)
20 SwiftData 0x00000002617a6f08 ModelContext.fetch<A>(_:) + 144 (ModelContext.swift:2534)
21 SwiftData 0x00000002617a6e70 dispatch thunk of ModelContext.fetch<A>(_:) + 56 (:-1)
22 AuditOS 0x00000001041af3f4 0x10419c000 + 78836
23 AuditOS 0x00000001041bebd5 0x10419c000 + 142293
24 AuditOS 0x00000001041bbbf5 0x10419c000 + 130037
25 AuditOS 0x00000001041d8be5 0x10419c000 + 248805
26 AuditOS 0x00000001041bde6d 0x10419c000 + 138861
27 libswift_Concurrency.dylib 0x00000001aa6bfe39 completeTaskWithClosure(swift::AsyncContext*, swift::SwiftError*) + 1 (Task.cpp:497)
The code in question looks like this:
func addRecord<T: MyDtoProtocol>(_ someDTO: T) async throws {
var zone: ZoneModel? = nil
let recordName = someDTO.recordNameType
let fetchDescriptor = FetchDescriptor<T.ModelType> (predicate: #Predicate {$0.recordName == recordName})
> var localEntitites: [T.ModelType] = try modelContext.fetch(fetchDescriptor) <---- I have isolated crash to this line.
Basically for each swiftdata model type I have associatedType for Data Transfer Object type and vice versa.
I am developing an Xcode app with a job feed, with profile view, with chat eg. I fetch using federatet queries to my microservices thru Apollo Router. Infront of the Apollo Router i Have a Kong that adds a X user ID, that the microservices use for personalized feed and other user info. The info is stored with SwiftData. My thought is that i should add a better way of controlling when i need to fetch. I have a “lastupdateAPI” with different entities (profile, profile picture eg). So when nothing has changed we do not fetch. But rather then using a own API for this, isnt ETag better? Or is it any other recommendations with Xcode Swiftui. Good strategies for not fetching what i already have?
I'm calling a method with the context as parameter, within the context's perform block – is this really not legal in Swift 6?
actor MyActor {
func bar(context: NSManagedObjectContext) { /* some code */ }
func foo(context: NSManagedObjectContext) {
context.performAndWait {
self.bar(context: context)
// WARN: Sending 'context' risks causing data races; this is an error in the Swift 6 language mode
// 'self'-isolated 'context' is captured by a actor-isolated closure. actor-isolated uses in closure may race against later nonisolated uses
// Access can happen concurrently
}
}
}
The warning appears when I call a method with a context parameter, within the performAndWait-block.
Background: In my app I have methods that takes in API data, and I need to call the same methods from multiple places with the same context to store it, and I do not want to copy paste the code and have hundreds of lines of duplicate code.
Is there a well-known "this is how you should do it" for situations like this?
This is related to a previous post I made, but it's a bit flimsy and got no response: https://developer.apple.com/forums/thread/770605
Am I misunderstanding the expected behavior here, or is there a bug in the behavior of @Attribute(.ephemeral) tagged SwiftData model properties?
The documentation for .ephemeral says "Track changes to this property but do not persist". I started using .ephemeral because @Transient was inhibiting SwiftUI from reacting to changes to the property through @Observable.
I am updating the value of my @Attribute(.ephemeral) property about once a second and I am seeing corresponding console log output showing the property as part of the generated CKRecord object. I then confirmed in the CloudKit dev portal that the .ephemeral property was added to the Record schema and contains real values. The behavior seems as though the .ephemeral property is being completely ignored.
This is observed in a new Xcode project using SwiftData with CloudKit, Xcode 16.2, macOS 15.3.1 and during Build & Run testing on physical devices.
Document based SwiftData apps do not autosave changes to the ModelContext at all. This issue has been around since the first release of this SwiftData feature.
In fact, the Apple WWDC sample project (https://developer.apple.com/documentation/swiftui/building-a-document-based-app-using-swiftdata) does not persist any data in its current state, unless one inserts modelContext.save() calls after every data change.
I have reported this under the feedback ID FB16503154, as it seemed to me that there is no feedback report about the fundamental issue yet.
Other posts related to this problem:
https://forums.developer.apple.com/forums/thread/757172
https://forums.developer.apple.com/forums/thread/768906
https://developer.apple.com/forums/thread/764189
I'm having some issues where only a subset of records appear in CloudKit dashboard after I have saved some records in my iOS app using NSPersistentCloudKitContainer. I have noticed that when I'm running my app using the development environment of my CloudKit container everything works smoothly and is uploaded as expected but when I'm using the production environment only a subset of records are actually uploaded.
I'm pulling my hair on how to debug this. -com.apple.CoreData.CloudKitDebug and -com.apple.CoreData.SQLDebug pukes out too much info in the console for me to pinpoint any issue.
One question I often see on DevForums and in my day DTS job is if a Core Data object managed by NSPersistentCloudKitContainer can be shared with other iCloud users.
The answer is yes but you need to do it using CloudKit API directly because NSPersistentCloudKitContainer doesn’t support CloudKit shared database (CKContainer.sharedCloudDatabase) today.
Assuming you have a Core Data object, let’s say a document, that you’d like to collaborate with your colleagues:
You are the document owner and can use NSPersistentCloudKitContainer to fully manages the document and synchronize it across your devices.
You can grab a CloudKit record associated with your document from NSPersistentCloudKitContainer using record(for:) or recordID(for:), and share it to your colleagues using UICloudSharingController. See our Sharing CloudKit Data with Other iCloud Users - https://developer.apple.com/documentation/cloudkit/sharing_cloudkit_data_with_other_icloud_users sample for how to share a CloudKit record.
After accepting the sharing, your colleague, as a participant, can view or edit the shared document. The document resides in the participant’s CloudKit shared database and you have to manage it with your own code.
When your colleague edits and saves the shared document, the changes go to the owner’s private database, and eventually synchronize to NSPersistentCloudKitContainer on the owner side.
As you can see, you need to implement #2 and #3 with your own code because NSPersistentCloudKitContainer can’t manage the data in the participant's shared database. If you have any difficulty after going through the above sample code, you can contact Apple’s DTS for help.
I'm working through the Develop In Swift tutorial at page
[https://developer.apple.com/tutorials/develop-in-swift/navigation-editing-and-relationships-conclusion)]
The tutorial has a one to many relationship between Friend and Movie (each friend can have at most one favorite movie and each movie can be the favorite for zero or more friends).
An exercise left to the student is to use an .onDelete on the movie detail page to delete that movie as favorite.
I modified the Form
Form {
TextField("Movie title", text: $movie.title)
DatePicker("Release date", selection: $movie.releaseDate, displayedComponents: .date)
if !movie.favoritedBy.isEmpty {
Section("Favorited by") {
ForEach(sortedFriends) { friend in
Text(friend.name)
}
.onDelete(perform: deleteFavorites(indexes:))
}
}
}
by adding the .onDelete clause
I added
private func deleteFavorites(indexes: IndexSet) {
for index in indexes {
context.delete(movie.favoritedBy[index])
}
}
to the view.
This does delete the favorite movie, but it also deletes the friend. My assumption is that the selected friend should then have no favorite movie rather than being deleted
There is an if in the Form that doesn't display the FAVORITED BY section if no friend has that movie as a favorite, but if I delete all the friends who had this movie as a favorite, the section remains (but is empty), until I exit the MovieDetail view and reload it
There is no answer for these exercises, so I could be doing it wrong.
EDIT: If I delete a movie using the app function to delete a movie, friends that have that movie as a favorite are not deleted and have their favorite movie set to None
I just released an App update the didn't touch ANYTHING to do with Core Data (nothing changed in our Coredata code for at least 8 months). The update uses SDK for iOS 18 and Xcode 16.2 and the app now requires iOS 18 and was a minor bug patch and UI improvements for recent iOS changes.
Since the update we are getting a steady trickle of users on iOS 18, some who allow the App to store data in iCloud (Cloudkit) and others who do not, all reporting that after the update to our recent release ALL their data is gone?!
I had not seen this on ANY device until today when I asked a friend who uses the App if they had the issue and it turned out they did, so I hooked their device up to Xcode and ALL the data in the CoreData database was gone?! They are NOT using iCloud. There were no errors or exceptions on Xcode console but a below code returned NO records at all?!
Chart is custom entity and is defined as:
@interface Chart : NSManagedObject {}
let moc = pc.viewContext
let chartsFetch = NSFetchRequest<NSFetchRequestResult>(entityName:"Charts") // Fetch all Charts
do {
let fetchedCharts = try moc.fetch(chartsFetch) as! [Chart]
for chart in fetchedCharts {
....
}
}
A break point inside the do on fetchedCharts show there are NO objects returned.
This is a serious issue and seems like an iOS 18 thing. I saw some people talking in here about NSFetchRequest issues with iOS 18. I need some guidance here from someone Apple engineer here who knows what the status of these NSFetchrequest bugs are and what possible workarounds are. Becasue this problem will grow for me as more users update to iOS 18.
When I try to promote schema to production, I get following error:
Cannot promote schema with empty type 'workspace', please delete the record type before attempting to migrate the schema again
However, in hierarchical root record sharing, I think it should be completely legit use case where there is empty root record (in my case workspace) to which other records reference through ->parent reference.
Am I missing something? Is this weird constraint imposed on CloudKit?
I am trying to test using Testflight and have set up a test with a user on an account I also own which is different to me developer account. The app I believe is running in production on a separate device and is working from a user point of view, however I am not able to query the data via the console. As I said I know the user id and password as tey are mine so even when I use the Act as user service it logs in but the query is empty. I'm assuming I'm not doing anything wrong its possibly an security issue that is preventing me accessing this account. My question to the group then is how do I verify the data that is being tested?
Hello,
I am trying to access my cloudkit database from the icloud developer dashboard but I am getting the following error:
Error looking up Developer Teams
XHR request failure
Please sign out and try again.
I tried signing out but the error persists,
Thanks
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.
I am using SwiftData for storage and have a view that uses the @Query property wrapper with a sort descriptor that points to a relationship on a model. In a release build on device running iOS 18.3, the app crashes.
This is the line that crashes:
@Query(sort: \Item.info.endDate, order: .reverse) private var items: [Item]
Item has a relationship to ItemInfo, which is where the endDate property is defined. This code works in debug and on a simulator.
In the project referenced here: https://github.com/lepolt/swiftdata-crash, change the scheme build configuration to “Release” and run on device. The app will crash.
Using Xcode Version 16.2 (16C5032a)
iPhone 12, iOS 18.3 (22D60)
I have a simple model
@Model
final class Movie: Identifiable {
#Index\<Movie\>(\[.name\])
var id = UUID()
var name: String
var genre: String?
init(name: String, genre: String?) {
self.name = name
self.genre = genre
}
}
I turned on SQL debugging by including '-com.apple.CoreData.SQLDebug 3' argument on launch.
When I fetch the data using the following code, it selects 3 records initially, but then also selects each record individually even though I am not referencing any other attributes.
var fetchDescriptor = FetchDescriptor\<Movie\>()
fetchDescriptor.propertiesToFetch = \[.id, .name\]
fetchDescriptor.fetchLimit = 3
do {
print("SELECT START")
movies = try modelContext.fetch(fetchDescriptor)
print("SELECT END")
} catch {
print("Failed to load Movie model.")
}
I see it selecting the 3 rows initially, but then it selects each one separately. Why would it do this on the initial fetch? I was hoping to select the data that I want to display and let the system select the entire record only when I access a variable that I did not initially fetch.
CoreData: annotation: fetch using NSSQLiteStatement <0x600002158af0> on entity 'Movie' with sql text 'SELECT 1, t0.Z_PK, t0.ZID, t0.ZNAME FROM ZMOVIE t0 LIMIT 3' returned 3 rows with values: (
"<NSManagedObject: 0x600002158d70> (entity: Movie; id: 0xa583c7ed484691c1 <x-coredata://71E60F4C-1A40-4DB7-8CD1-CD76B4C11949/Movie/p1>; data: <fault>)",
"<NSManagedObject: 0x600002158d20> (entity: Movie; id: 0xa583c7ed482691c1 <x-coredata://71E60F4C-1A40-4DB7-8CD1-CD76B4C11949/Movie/p2>; data: <fault>)",
"<NSManagedObject: 0x600002158f00> (entity: Movie; id: 0xa583c7ed480691c1 <x-coredata://71E60F4C-1A40-4DB7-8CD1-CD76B4C11949/Movie/p3>; data: <fault>)"
)
CoreData: annotation: fetch using NSSQLiteStatement <0x600002154d70> on entity 'Movie' with sql text 'SELECT 0, t0.Z_PK, t0.Z_OPT, t0.ZGENRE, t0.ZID, t0.ZNAME FROM ZMOVIE t0 WHERE t0.Z_PK = ? ' returned 1 rows
CoreData: annotation: with values: (
"<NSSQLRow: 0x600000c89500>{Movie 1-1-1 genre=\"Horror\" id=4C5CB4EB-95D7-4DC8-B839-D4F2D2E96ED0 name=\"A000036\" and to-manys=0x0}"
)
This all happens between the SELECT START and SELECT END print statements. Why is it fulfilling the faults immediately?
Is it possible to track history using the new HistoryDescriptor feature in SwiftData? Or can I only get the current most recent data? Or is it possible to output the changed data itself, along with timestamps?
I am hoping that it is possible to track by a standard feature like NSPersistentHistoryTransaction in CoreData.
Do we still have to use a method in SwiftData that creates more tracking data itself?
I have two recordTypes in CloudKit: Author and Book. The Book records have their parent property set to an Author, enabling hierarchical record sharing (i.e., if an Author record is shared, the participant can see all books associated with that author in their shared database).
When syncing with CKSyncEngine, I was expecting handleFetchedRecordZoneChanges to deliver all Author records before their associated Book records. However, unless I’m missing something, the order appears to be random.
This randomness forces me to handle two codepaths in my app (opposed to just one) to replicate CloudKit references in my local persistency storage:
Book arrives before its Author → I store the Book but defer setting its parent reference until the corresponding Author arrives.
Author arrives before its Books → I can immediately set the parent reference when each Book arrives.
Is there a way to ensure that Author records always arrive before Book records when syncing with CKSyncEngine? Or is this behavior inherently unordered and I have to implement two codepaths?
Hi everyone,
I've recently implemented CKSyncEngine in my app, and I have two questions regarding its behavior:
Duplicate FetchedRecordZoneChanges After Sending Changes:
I’ve noticed that the engine sometimes receives a FetchedRecordZoneChanges event containing modifications and deletions that were just sent by the same device a few moments earlier. This event arrives after the SentRecordZoneChanges event, and both events share the same recordChangeTag, which results in double-handling the record.
Is this expected behavior? I’d like to confirm if this is how CKSyncEngine works or if I might be overlooking something.
Handling Initial Sync with a "Sync Screen":
When a user opens the app for the first time and already has data stored in iCloud, I need to display a "Sync Screen" temporarily to prevent showing partial data or triggering abrupt, rapid UI changes.
I’ve found that canceling current operations, then awaiting sendChanges() and fetchChanges() works well to ensure data is fully synced before dismissing the sync screen:
displaySyncScreen = true
await syncEngine.cancelOperations()
try await syncEngine.sendChanges()
try await syncEngine.fetchChanges()
displaySyncScreen = false
However, I’m unsure if canceling operations like this could lead to data loss or other issues. Is this a safe approach, or would you recommend a better strategy for handling this initial sync state?
Hello,
I'm using CoreData + CloudKit and I am facing the following error 134100 "The managed object model version used to open the persistent store is incompatible with the one that was used to create the persistent store."
All my schema updates are composed of adding optional attributes to existing entities, adding non-optional attributes (with default value) to existing entities or adding new entities Basically, only things that lightweight migrations can handle.
Every time I update the schema, I add a new model version of xcdatamodel - who only has a single configuration (the "Default" one). And I also deploy the updated CloudKit schema from the dashboard.
It worked up to v3 of my xcdatamodel, but started to crash for a few users at v4 when I added 16 new attributes (in total) to 4 existing entities.
Then again at v5 when I added 2 new optional attributes to 1 existing entity.
I'm using a singleton and here is the code:
private func generateCloudKitContainer() -> NSPersistentCloudKitContainer {
let container = NSPersistentCloudKitContainer(name: "MyAppModel")
let fileLocation = URL(...)
let description = NSPersistentStoreDescription(url: fileLocation)
description.shouldMigrateStoreAutomatically = true
description.setOption(true as NSNumber, forKey: NSPersistentHistoryTrackingKey)
description.setOption(true as NSNumber, forKey: NSPersistentStoreRemoteChangeNotificationPostOptionKey)
let options = NSPersistentCloudKitContainerOptions(containerIdentifier: "iCloud.com.company.MyApp")
options.databaseScope = .private
description.cloudKitContainerOptions = options
container.persistentStoreDescriptions = [description]
container.viewContext.automaticallyMergesChangesFromParent = true
container.loadPersistentStores { description, error in
container.viewContext.mergePolicy = NSMergePolicy(merge: .mergeByPropertyObjectTrumpMergePolicyType)
if let error {
// Error happens here!
}
}
return container
}
I can't reproduce it yet. I don't really understand what could lead to this error.