I'm developing an app that uses CloudKit synchronization with SwiftData and on visionOS I added an App Settings bundle. I have noticed that sometimes, when the app is open and the user changes a setting from the App Settings bundle, the following fatal error occurs:
SwiftData/BackingData.swift:831: Fatal error: This model instance was destroyed by calling ModelContext.reset and is no longer usable.
The setting is read within the App struct in the visionOS app target using @AppStorage and this value is in turn used to set the passthrough video dimming via the .preferredSurroundingsEffect modifier. The setting allows the user to specify the dimming level as dark, semi dark, or ultra dark.
The fatal error appears to occur intermittently although the first time it was observed was after adding the settings bundle. As such, I suspect there is some connection between those code changes and this fatal error even though they do not directly relate to SwiftData.
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 have an app that from day 1 has used Swiftdata and successfully sync'd across devices with Cloudkit. I have added models to the data in the past and deployed the schema and it continued to sync across devices. Sometime I think in June.2025 I added a new model and built out the UI to display and manage it. I pushed a version to Test Flight (twice over a matter of 2 versions and a couple of weeks) and created objects in the new model in Test Flight versions of the app which should push the info to Cloudkit to update the schema.
When I go to deploy the schema though there are no changes. I confirmed in the app that Cloudkit is selected and it's point to the correct container. And when I look in Cloudkit the new model isn't listed as an indes.
I've pushed deploy schema changes anyway (more than once) and now the app isn't sync-ing across devices at all (even the pre-existing models aren't sync-ing across devices).
I even submitted the first updated version to the app store and it was approved and released. I created objects in the new model in production which I know doesn't create the indexes in the development environment. But this new model functions literally everywhere except Cloudkit and I don't know what else to do to trigger an update.
My entity has a startDate (NSTime) attribute where I use the date and time in my detail display of the entity.
And in my list, I need to group my entities by day (YYMMDD) based on the start date; and I want to ensure that it can adapt to the region where the user is currently (e.g. if user travels or migrate, the YYMMDD should be adapted based on the current region). Does Core Data SectionedFetchRequest supports strftime() functions from SQLite (https://sqlite.org/lang_datefunc.html) or what is an effective alternative sectioned fetch in my case?
Hi everyone,
I’ve been working on migrating my app (SwimTimes, which helps swimmers track their times) to use Core Data + CKSyncEngine with Swift 6.
After many iterations, forum searches, and experimentation, I’ve created a focused sample project that demonstrates the architecture I’m using.
The good news:
👉 I believe the crashes I was experiencing are now solved, and the sync behavior is working correctly.
👉 The demo project compiles and runs cleanly with Swift 6.
However, before adopting this as the final architecture, I’d like to ask the community (and hopefully Apple engineers) to validate a few critical points, especially regarding Swift 6 concurrency and Core Data contexts.
Architecture Overview
Persistence layer: Persistence.swift sets up the Core Data stack with a main viewContext and a background context for CKSyncEngine.
Repositories: All Core Data access is abstracted into repository classes (UsersRepository, SwimTimesRepository), with async/await methods.
SyncEngine: Wraps CKSyncEngine, handles system fields, sync tokens, and bridging between Core Data entities and CloudKit records.
ViewModels: Marked @MainActor, exposing @Published arrays for SwiftUI. They never touch Core Data directly, only via repositories.
UI: Simple SwiftUI views bound to the ViewModels.
Entities:
UserEntity → represents swimmers.
SwimTimeEntity → times linked to a user (1-to-many).
Current Status
The project works and syncs across devices. But there are two open concerns I’d like validated:
Concurrency & Memory Safety
Am I correctly separating viewContext (main/UI) vs. background context (used by CKSyncEngine)?
Could there still be hidden risks of race conditions or memory crashes that I’m not catching?
Swift 6 Sendable Compliance
Currently, I still need @unchecked Sendable in the SyncEngine and repository layers.
What is the recommended way to fully remove these workarounds and make the code safe under Swift 6’s stricter concurrency rules?
Request
Please review this sample project and confirm whether the concurrency model is correct.
Suggest how I can remove the @unchecked Sendable annotations safely.
Any additional code improvements or best practices would also be very welcome — the intention is to share this as a community resource.
I believe once finalized, this could serve as a good reference demo for Core Data + CKSyncEngine + Swift 6, helping others migrate safely.
Environment
iOS 18.5
Xcode 16.4
macOS 15.6
Swift 6
Sample Project
Here is the full sample project on GitHub:
👉 [https://github.com/jarnaez728/coredata-cksyncengine-swift6]
Thanks a lot for your time and for any insights!
Best regards,
Javier Arnáez de Pedro
Users have been reporting that the TestFlight version of my app (compiled with Xcode 26 Beta 6 17A5305f) is sometimes crashing on startup. Upon investigating their ips files, it looks like Core Data is locking up internally during its initialization, resulting in iOS killing my app. I have not recently changed my Core Data initialization logic, and it's unclear how I should proceed.
Is this a known issue? Any recommended workaround? I have attached the crash stack below.
Thanks!
crash_log.txt
If Cloudkit is enabled, SwiftData @Query operation hangs when the View scenePhase becomes active.
Seems like the more @Query calls you have, the more it hangs.
This has been first documented some time ago, but in typical Apple style, it has not been addressed or even commented on.
https://developer.apple.com/forums/thread/761434
If I use <FetchRequest.returnsDistinctResults> with unique "identifier" property, and there happened to be multiple NSManagedObjects in Core Data that contains the same "identifier", does the FetchRequest retrieve the latest modified/created object?
Is there a way to define the <FetchRequest.returnsDistinctResults> logic to be based on another property (e.g. "creationDate" / "modifiedDate") and the ascension order?
Topic:
App & System Services
SubTopic:
iCloud & Data
hi,
in my app, i have created and pushed CKRecords to the public database. others using the app have pushed CKRecords as well.
is there any way i can query iCloud for "all the CKRecords that i created?"
thanks,
DMG
Topic:
App & System Services
SubTopic:
iCloud & Data
This simple test fails in my project. Similar code in my application also crashes.
How do I debug the problem?
What project settings are required. I have added SwiftData as a framework to test (and application) targets?
Thanks,
The problem is with:
modelContext.insert(item)
Thread 1: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)
import XCTest
import SwiftData
@Model
class FakeModel {
var name: String
init(name: String) { self.name = name }
}
@MainActor
final class FakeModelTests: XCTestCase {
var modelContext: ModelContext!
override func setUp() {
super.setUp()
do {
let container = try ModelContainer(for: FakeModel.self, configurations: ModelConfiguration(isStoredInMemoryOnly: true))
modelContext = container.mainContext
} catch {
XCTFail("Failed to create ModelContainer: \(error)")
modelContext = nil
}
}
func testSaveFetchDeleteFakeItem() {
guard let modelContext = modelContext else {
XCTFail("ModelContext must be initialized")
return
}
let item = FakeModel(name: "Test")
modelContext.insert(item)
let fetchDescriptor = FetchDescriptor<FakeModel>()
let items = try! modelContext.fetch(fetchDescriptor)
XCTAssertEqual(items.count, 1)
XCTAssertEqual(items.first?.name, "Test")
modelContext.delete(item)
let itemsAfterDelete = try! modelContext.fetch(fetchDescriptor)
XCTAssertEqual(itemsAfterDelete.count, 0)
}
}
Hi,
I am currently experiencing some trouble when using parent model property in a predicate of a child model.
I have an Item class that define parent-child relationship:
@Model class Item {
var timestamp: Date
@Relationship(inverse: \Item.children)
var parent: Item?
var children: [Item]
init(parent: Item? = nil, children: [Item] = [], timestamp: Date = .now) {
self.parent = parent
self.children = children
self.timestamp = timestamp
}
}
I subclass this model like that:
@available(iOS 26, *)
@Model final class CollectionItem: Item { /* ... */ }
When i make a Query in my View like that the system crashes:
@Query(
filter: #Predicate<CollectionItem> { $0.parent == nil },
sort: \CollectionItem.name,
)
private var collections: [CollectionItem]
CrashReportError: Fatal Error in DataUtilities.swift
AppName crashed due to fatalError in DataUtilities.swift at line 85.
Couldn't find \CollectionItem.<computed 0x000000034005d4e8 (Optional<Item>)> on CollectionItem with fields [SwiftData.Schema.PropertyMetadata(name: "name", keypath: \CollectionItem.<computed 0x000000034003c120 (String)>, defaultValue: nil, metadata: nil), SwiftData.Schema.PropertyMetadata(name: "icon", keypath: \CollectionItem.<computed 0x000000034003ca04 (Optional<String>)>, defaultValue: nil, metadata: nil), SwiftData.Schema.PropertyMetadata(name: "timestamp", keypath: \Item.<computed 0x0000000340048018 (Date)>, defaultValue: nil, metadata: nil), SwiftData.Schema.PropertyMetadata(name: "parent", keypath: \Item.<computed 0x0000000340048a4c (Optional<Item>)>, defaultValue: nil, metadata: Optional(Relationship - name: , options: [], valueType: Any, destination: , inverseName: nil, inverseKeypath: Optional(\Item.<computed 0x0000000340048fe8 (Array<Item>)>))), SwiftData.Schema.PropertyMetadata(name: "children", keypath: \Item.<computed 0x0000000340048fe8 (Array<Item>)>, defaultValue: nil, metadata: nil)]
When I query as Item it works but then i cannot sort on CollectionItem field and must add unnecessary down casting:
@Query(
filter: #Predicate<Item> { $0.parent == nil && $0 is CollectionItem },
)
private var items: [Item]
Am I missing something? Is it a platform limitation or a known issue?
My Code:
let op = CKModifyRecordsOperation(recordIDsToDelete:recordIDsToDelete)
op.modifyRecordsCompletionBlock = { _, deleteRecordIDs, error in
if error == nil {
print("successful delete deleteRecordIDS = \(deleteRecordIDs)")
} else {
print("delete error = \(error?.localizedDescription)")
}
}
op.database = CKContainer.default().privateCloudDatabase
op.qualityOfService = .userInitiated
CKContainer.default().privateCloudDatabase.add(op)
My problem is that CKRecord are not deleted once I reinstall the app: when I reinstall the app and try to delete a CloudKit record, the method is executed successfully (error is nil) but the records are still in CloudKit Dashboards.
Topic:
App & System Services
SubTopic:
iCloud & Data
Tags:
CloudKit
CloudKit Dashboard
CloudKit Console
I have some code which handles doing some computation on a background thread before updating Core Data NSManagedObjects by using the NSManagedObjectContext.perform functions.
This code is covered in Sendable warnings in Xcode 26 (beta 6) because my NSManagedObject subclasses (autogenerated) are non-Sendable and NSManagedObjectContext.perform function takes a Sendable closure.
But I can't really figure out what I should be doing. I realize this pattern is non-ideal for Swift concurrency, but it's what Core Data demands AFAIK. How do I deal with this?
let moc = object.managedObjectContext!
try await moc.perform {
object.completed = true // Capture of 'object' with non-Sendable type 'MySpecialObject' in a '@Sendable' closure
try moc.save()
}
Thanks in advance for your help!
"No records found"
If I create a new record on the console, I can copy the record name.
I can then query for recordName and get that individual record back.
BUT no other queries work. I cannot query all records. I cannot query by individual property.
Just returns "no records found"
Seems like my indexes got messed up. Is there a way to reset indexes on prod?
This is on a coredata.cloudkit managed zone.
I have a UIKit app where I've adopted SwiftData and I'm struggling with a crash coming in from some of my users. I'm not able to reproduce it myself and as it only happens to a small fraction of my user base, it seems like a race condition of some sort.
This is the assertion message:
SwiftData/DefaultStore.swift:453: Fatal error: API Contract Violation: Editors must register their identifiers before invoking operations on this store SwiftData.DefaultStore: 00CF060A-291A-4E79-BEC3-E6A6B20F345E did not. (ID is unique per crash)
This is the ModelActor that crashes:
@available(iOS 17, *)
@ModelActor
actor ConsumptionDatabaseStorage: ConsumptionSessionStorage {
struct Error: LocalizedError {
var errorDescription: String?
}
private let sortDescriptor = [SortDescriptor(\SDConsumptionSession.startTimeUtc, order: .reverse)]
static func createStorage(userId: String) throws -> ConsumptionDatabaseStorage {
guard let appGroupContainer = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: UserDefaults.defaultAppGroupIdentifier) else {
throw Error(errorDescription: "Invalid app group container ID")
}
func createModelContainer(databaseUrl: URL) throws -> ModelContainer {
return try ModelContainer(for: SDConsumptionSession.self, SDPriceSegment.self, configurations: ModelConfiguration(url: databaseUrl))
}
let databaseUrl = appGroupContainer.appendingPathComponent("\(userId).sqlite")
do {
return self.init(modelContainer: try createModelContainer(databaseUrl: databaseUrl))
} catch {
// Creating the model storage failed. Remove the database file and try again.
try? FileManager.default.removeItem(at: databaseUrl)
return self.init(modelContainer: try createModelContainer(databaseUrl: databaseUrl))
}
}
func isStorageEmpty() async -> Bool {
(try? self.modelContext.fetchCount(FetchDescriptor<SDConsumptionSession>())) ?? 0 == 0 // <-- Crash here!
}
func sessionsIn(interval: DateInterval) async throws -> [ConsumptionSession] {
let fetchDescriptor = FetchDescriptor(predicate: #Predicate<SDConsumptionSession> { sdSession in
if let startDate = sdSession.startTimeUtc {
return interval.start <= startDate && interval.end > startDate
} else {
return false
}
}, sortBy: self.sortDescriptor)
let consumptionSessions = try self.modelContext.fetch(fetchDescriptor) // <-- Crash here!
return consumptionSessions.map { ConsumptionSession(swiftDataSession: $0) }
}
func updateSessions(sessions: [ConsumptionSession]) async throws {
if #unavailable(iOS 18) {
// Price segments are duplicated if re-inserted so unfortunately we have to delete and reinsert sessions.
// On iOS 18, this is enforced by the #Unique macro on SDPriceSegment.
let sessionIds = Set(sessions.map(\.id))
try self.modelContext.delete(model: SDConsumptionSession.self, where: #Predicate<SDConsumptionSession> {
sessionIds.contains($0.id)
})
}
for session in sessions {
self.modelContext.insert(SDConsumptionSession(consumptionSession: session))
}
if self.modelContext.hasChanges {
try self.modelContext.save()
}
}
func deleteAllSessions() async {
if #available(iOS 18, *) {
try? self.modelContainer.erase()
} else {
self.modelContainer.deleteAllData()
}
}
}
The actor conforms to this protocol:
protocol ConsumptionSessionStorage {
func isStorageEmpty() async -> Bool
func hasCreditCardSessions() async -> Bool
func sessionsIn(interval: DateInterval) async throws -> [ConsumptionSession]
func updateSessions(sessions: [ConsumptionSession]) async throws
func deleteAllSessions() async
}
The crash is coming in from line 30 and 41, in other words, when trying to fetch data from the database. There doesn't seem to be any common trait for the crashes. They occur across iOS versions and device types.
Any idea what might cause this?
I've been seeing something that I find odd when using two SwiftData models where if I have one model (book, in this case) that has an optional array of another model (page, in this case), the optional array starts out as set to nil, but after about 20 seconds it updates to being an empty array.
I see it in Previews and after building.
Is this expected behavior? Should I just assume that if there is an optional array in my model it will eventually be initialized to an empty array?
Code is below.
import SwiftUI
import SwiftData
@Model
final class Book {
var title: String = "New Book"
@Relationship var pages: [Page]? = nil
init(title: String) {
self.title = title
}
}
@Model
final class Page {
var content: String = "Page Content"
var book: Book? = nil
init() {
}
}
struct ContentView: View {
@Environment(\.modelContext) private var modelContext
@Query private var books: [Book]
var body: some View {
NavigationSplitView {
List {
ForEach(books) { book in
NavigationLink {
Text("\(book.title)")
Text(book.pages?.debugDescription ?? "pages is nil")
} label: {
Text("\(book.title)")
Spacer()
Text("\(book.pages?.count.description ?? "pages is nil" )")
}
}
}
HStack {
Button("Clear Data") {
clearData()
}
Button("Add Book") {
addBook()
}
}
.navigationSplitViewColumnWidth(min: 180, ideal: 200)
} detail: {
Text("Select an item")
}
}
private func clearData() {
for book in books {
modelContext.delete(book)
}
try? modelContext.save()
}
private func addBook() {
let newBook = Book(title: "A New Book")
modelContext.insert(newBook)
}
}
@main
struct BookPageApp: App {
var sharedModelContainer: ModelContainer = {
let schema = Schema([Book.self, Page.self])
let modelConfiguration = ModelConfiguration(schema: schema, isStoredInMemoryOnly: false)
do {
return try ModelContainer(for: schema, configurations: [modelConfiguration])
} catch {
fatalError("Could not create ModelContainer: \(error)")
}
}()
var body: some Scene {
WindowGroup {
ContentView()
}
.modelContainer(sharedModelContainer)
}
}
#Preview {
ContentView()
.modelContainer(for: Book.self, inMemory: true)
}
Environment
visionOS 26
Xcode 26
Issue
I am experiencing crash when trying to access a [String] from a @Model data, after dismissing an immersiveSpace and opening a WindowGroup.
This crash only occurs when trying to access the [String] property of my Model. It works fine with other properties.
Thread 1: Fatal error: This backing data was detached from a context without resolving attribute faults: PersistentIdentifier(...)
Steps to Reproduce
Open WindowGroup
Dismiss window, open ImmersiveSpace
Dismiss ImmersiveSpace, reopen WindowGroup
Any guidance would be appreciated!
@main
struct MyApp: App {
var body: some Scene {
WindowGroup(id: "main") {
ContentView()
}
.modelContainer(for: [Item.self])
ImmersiveSpace(id: "immersive") {
ImmersiveView()
}
}
}
// In SwiftData model
@Model
class Item {
var title: String = "" // Accessing this property works fine
var tags: [String] = []
@storageRestrictions(accesses: _$backingData, initializes: _tags)
init(initialValue) {
_$backingData.setValue(forKey: \. tags, to: initialValue)
_tags =_ SwiftDataNoType()
}
get {
_$observationRegistrar.access(self, keyPath: \.tags)
**return self getValue(forkey: \.tags)** // Crashes here
}
Hello,
I'm trying to work on an iPadOS and macOS app that will rely on the document-based system to create some kind of orientation task to follow.
Let say task1.myfile will be a check point regulation from NYC to SF and task2.myfile will be a visit as many key location as you can in SF.
The file represent the specific landmark location and rules of the game.
And once open, I will be able to read KML/GPS file to evaluate their score based with the current task.
But opened GPS files does not have to be stored in the task file itself, it stay alongside.
I wanted to use that scenario to experiment with SwiftData (I'm a long time CoreData user, I even wrote my own WebDAV based persistent store back in the day), and so, mix both on file and in memory persistent store, with distribution based on object class.
With CoreData it would have been possible, but I do not see how to achieve that with SwiftData and DocumentGroup integration.
Any idea how to do that?
I have a ModelActor that creates a hierarchy of models and returns a PersistentIdentifier for the root. I'd like to do that in a transaction, but I don't know of a good method of getting that identifier if the models are created in a transaction.
For instance, an overly simple example:
func createItem(timestamp: Date) throws -> PersistentIdentifier {
try modelContext.transaction {
let item = Item(timestamp: timestamp)
modelContext.insert(item)
}
// how to return item.persistentModelID?
}
I can't return the item.persistentModelID from the transaction closure and even if I could, it will be a temporary ID until after the transaction is executed.
I can't create the Item outside the transaction and just have the transaction do an insert because swift will raise a data race error if you then try to return item.persistentModelID.
Is there any way to do this besides a modelContext.fetch* with separate unique identifiers?
I work on an app that saves data to the Documents folder in the users iCloud Drive. This uses the iCloud -> iCloud Documents capability with a standard container.
We've noticed an issue where a user will delete the apps data by doing to Settings > {Name} > iCloud > Storage > App Name > select "delete data from iCloud", and then our app can no longer write to or create the Documents folder.
Once that happens, we get this error:
Error Domain=NSCocoaErrorDomain Code=513 "You don't have permission to save the file "Documents" in the folder "iCloud~your~bundle~identifier"." UserInfo={NSFilePath=/private/var/mobile/Library/Mobile Documents/iCloud~your~bundle~identifier/Documents, NSURL=file:///private/var/mobile/Library/Mobile%20Documents/iCloud~your~bundle~identifier/Documents, NSUnderlyingError=0x1102c7ea0 {Error Domain=NSPOSIXErrorDomain Code=13 "Permission denied"}}
This is reproducible using the sample project here https://developer.apple.com/documentation/uikit/synchronizing-documents-in-the-icloud-environment.
Steps to reproduce in that project:
Tap the plus sign in the top right corner to create a new document
Add a document name and tap "Save to Documents"
Go to Settings > {Name} > iCloud > Storage > SimpleiCloudDocument App Name > select "delete data from iCloud"
Reopen the app and repeat steps 1-2
Observe error on MainViewController+Document.swift:59
Deleting and reinstalling the app doesn't seem to help.
Topic:
App & System Services
SubTopic:
iCloud & Data
What have people's experience with converting locally stored app data to a more browser based accessible format? Firebase seems expensive, Subabase a bit more challenging, and CloudKit too restrictive.