Here is what I thought
I want to give each user a unique container, when the user login or register, the user could isolate their data in specific container.
I shared the container in a singleton actor, I found it's possible to update the container in that actor.
But I think it won't affect the modelContext which is in the Environment.
Does SwiftData allow me or recommend to do that?
SwiftData
RSS for tagSwiftData is an all-new framework for managing data within your apps. Models are described using regular Swift code, without the need for custom editors.
Posts under SwiftData tag
200 Posts
Selecting any option will automatically load the page
Post
Replies
Boosts
Views
Activity
My app has three main SwiftData models: Collection, SavedItem, and Extract.
A Collection can contain subcollections (folders within folders) and SavedItems (files).
Each SavedItem can have child Extracts.
I'm preparing for the ability for users to be able to share Collections with each other.
Currently, my architecture treats each Collection as the root of its own CloudKit zone (a root parent Collection and all of its items and subcollections live in 1 zone).
This makes sharing and isolation straightforward, but it also means that moving a SavedItem or subcollection between Collections involves moving it across zones.
I’m trying to figure out the best pattern for handling these cross-zone moves while keeping data integrity, relationships, and sharing intact.
My understanding is that in CloudKit, and moving a record from Zone A to Zone B would require deleting it from Zone A and recreating it in Zone B - while somehow maintaining the link back to my local SwiftData store.
Has anyone run into this or know how best I should handle it?
Updated the phone to iOS 26.1 and now the app is not working anymore, even previously approved version published on App Store which works perfectly on iOS 26.0.1, and iOS 18+.
I deleted the app from the phone and installed fresh from App Store, still the same.
Logic is that on start app copies previously prepared SwiftData store file (using the same models) from app bundle to Documents directory and uses it.
Currently app just hungs with loader spinner spinning as it can t connect to the store.
Getting this error in console when running from Xcode on real device with iOS 26.1 installed:
CoreData: error:
CoreData: error: Store failed to load. <NSPersistentStoreDescription: 0x10c599e90> (type: SQLite, url: file:///var/mobile/Containers/Data/Application/DA32188D-8887-48F7-B828-1F676C8FBEF8/Documents/default.store)
with error = Error Domain=NSCocoaErrorDomain Code=134140
"Persistent store migration failed, missing mapping model."
UserInfo={sourceModel=(<NSManagedObjectModel: 0x10c503ac0>) isEditable 0,
entities { /// there goes some long models description
addPersistentStoreWithType:configuration:URL:options:error: returned error NSCocoaErrorDomain (134140)
Any help or workaround will be greatly appreciated.
I have one target building and filling the SwiftData store and then copying the same store file to another target of the app to use the contents.
That worked fine from iOS 17 to iOS 26.0.1
Under iOS 26.1 I am getting following error:
CoreData: error:
This store file was previously used on a build with Persistence-1522 but is now running on a build with Persistence-1518.
file:///Users/xxx/Library/Developer/CoreSimulator/Devices/0FE92EA2-57FA-4A5E-ABD0-DAB4DABC3E02/data/Containers/Data/Application/B44D3256-9B09-4A60-94E2-C5F11A6519E7/Documents/default.store
What does it mean and how to get back to working app under iOS 26.1?
Hello, I've a question about performance when trying to render lots of items coming from SwiftData via a @Query on a SwiftUI List. Here's my setup:
// Item.swift:
@Model final class Item: Identifiable {
var timestamp: Date
var isOptionA: Bool
init() {
self.timestamp = Date()
self.isOptionA = Bool.random()
}
}
// Menu.swift
enum Menu: String, CaseIterable, Hashable, Identifiable {
var id: String { rawValue }
case optionA
case optionB
case all
var predicate: Predicate<Item> {
switch self {
case .optionA: return #Predicate { $0.isOptionA }
case .optionB: return #Predicate { !$0.isOptionA }
case .all: return #Predicate { _ in true }
}
}
}
// SlowData.swift
@main
struct SlowDataApp: App {
var sharedModelContainer: ModelContainer = {
let schema = Schema([Item.self])
let modelConfiguration = ModelConfiguration(schema: schema, isStoredInMemoryOnly: false)
return try! ModelContainer(for: schema, configurations: [modelConfiguration])
}()
var body: some Scene {
WindowGroup {
ContentView()
}
.modelContainer(sharedModelContainer)
}
}
// ContentView.swift
struct ContentView: View {
@Environment(\.modelContext) private var modelContext
@State var selection: Menu? = .optionA
var body: some View {
NavigationSplitView {
List(Menu.allCases, selection: $selection) { menu in
Text(menu.rawValue).tag(menu)
}
} detail: {
DemoListView(selectedMenu: $selection)
}.onAppear {
// Do this just once
// (0..<15_000).forEach { index in
// let item = Item()
// modelContext.insert(item)
// }
}
}
}
// DemoListView.swift
struct DemoListView: View {
@Binding var selectedMenu: Menu?
@Query private var items: [Item]
init(selectedMenu: Binding<Menu?>) {
self._selectedMenu = selectedMenu
self._items = Query(filter: selectedMenu.wrappedValue?.predicate,
sort: \.timestamp)
}
var body: some View {
// Option 1: touching `items` = slow!
List(items) { item in
Text(item.timestamp.description)
}
// Option 2: Not touching `items` = fast!
// List {
// Text("Not accessing `items` here")
// }
.navigationTitle(selectedMenu?.rawValue ?? "N/A")
}
}
When I use Option 1 on DemoListView, there's a noticeable delay on the navigation. If I use Option 2, there's none. This happens both on Debug builds and Release builds, just FYI because on Xcode 16 Debug builds seem to be slower than expected: https://indieweb.social/@curtclifton/113273571392595819
I've profiled it and the SwiftData fetches seem blazing fast, the Hang occurs when accessing the items property from the List. Is there anything I'm overlooking or it's just as fast as it can be right now?
Hi everyone,
I'm looking for the correct architectural guidance for my SwiftData implementation.
In my Swift project, I have dedicated async functions for adding, editing, and deleting each of my four models. I created these functions specifically to run certain logic whenever these operations occur. Since these functions are asynchronous, I call them from the UI (e.g., from a button press) by wrapping them in a Task.
I've gone through three different approaches and am now stuck.
Approach 1: @MainActor Functions
Initially, my functions were marked with @MainActor and worked on the main ModelContext. This worked perfectly until I added support for App Intents and Widgets, which caused the app to crash with data race errors.
Approach 2: Passing ModelContext as a Parameter
To solve the crashes, I decided to have each function receive a ModelContext as a parameter. My SwiftUI views passed the main context (which they get from @Environment(\.modelContext)), while the App Intents and Widgets created and passed in their own private context. However, this approach still caused the app to crash sometimes due to data race errors, especially during actions triggered from the main UI.
Approach 3: Creating a New Context in Each Function
I moved to a third approach where each function creates its own ModelContext to work on. This has successfully stopped all crashes. However, now the UI actions don't always react or update. For example, when an object is added, deleted, or edited, the change isn't reflected in the UI. I suspect this is because the main context (driving the UI) hasn't been updated yet, or because the async function hasn't finished its work.
My Question
I'm not sure what to do or what the correct logic should be. How should I structure my data operations to support the main UI, Widgets, and App Intents without causing crashes or UI update failures?
Here is the relevant code using my third (and current) approach. I've shortened the helper functions for brevity.
// MARK: - SwiftData Operations
extension DatabaseManager {
/// Creates a new assignment and saves it to the database.
public func createAssignment(
name: String, deadline: Date, notes: AttributedString,
forCourseID courseID: UUID, /*...other params...*/
) async throws -> AssignmentModel {
do {
let context = ModelContext(container)
guard let course = findCourse(byID: courseID, in: context) else {
throw DatabaseManagerError.itemNotFound
}
let newAssignment = AssignmentModel(
name: name, deadline: deadline, notes: notes, course: course, /*...other properties...*/
)
context.insert(newAssignment)
try context.save()
// Schedule notifications and add to calendar
_ = try? await scheduleReminder(for: newAssignment)
newAssignment.calendarEventIDs = await CalendarManager.shared.addEventToCalendar(for: newAssignment)
try context.save()
await MainActor.run {
WidgetCenter.shared.reloadTimelines(ofKind: "AppWidget")
}
return newAssignment
} catch {
throw DatabaseManagerError.saveFailed
}
}
/// Finds a specific course by its ID in a given context.
public func findCourse(byID id: UUID, in context: ModelContext) -> CourseModel? {
let predicate = #Predicate<CourseModel> { $0.id == id }
let fetchDescriptor = FetchDescriptor<CourseModel>(predicate: predicate)
return try? context.fetch(fetchDescriptor).first
}
}
// MARK: - Helper Functions (Implementations omitted for brevity)
/// Schedules a local user notification for an event.
func scheduleReminder(for assignment: AssignmentModel) async throws -> String {
// ... Full implementation to create and schedule a UNNotificationRequest
return UUID().uuidString
}
/// Creates a new event in the user's selected calendars.
extension CalendarManager {
func addEventToCalendar(for assignment: AssignmentModel) async -> [String] {
// ... Full implementation to create and save an EKEvent
return [UUID().uuidString]
}
}
Thank you for your help.
I'm experiencing a critical issue with SwiftData custom migrations where objects created during migration appear to be inserted successfully but aren't persisted or found by queries after migration completes. The migration logs show objects being created, but subsequent queries return zero results.
I'm migrating from schema version V2 to V2_5, which involves:
Renaming Person class to GroupData
Keeping the same data structure but changing the class name while keeping the old class.
Using a custom migration stage to copy data from old to new schema
Below is an extract of my two schema and migration plan:
Environment:
Xcode 16.0,
iOS 18.0,
Swift 6.0
SchemaV2
enum LinkMapV2: VersionedSchema {
static let versionIdentifier: Schema.Version = .init(2, 0, 0)
static var models: [any PersistentModel.Type] {
[AnnotationData.self, Person.self, History.self]
}
@Model
final class Person {
@Attribute(.unique) var id: UUID
var name: String
var photo: String
var requirement: String
var statue: Bool
var annotationId: UUID?
var number: Int = 0
init(id: UUID = UUID(), name: String = "", photo: String = "", requirement: String = "", status: Bool = false, annotationId: UUID? = nil, number: Int = 0) {
self.id = id
self.name = name
self.photo = photo
self.requirement = requirement
self.statue = status
self.annotationId = annotationId
self.number = number
}
}
}
Schema V2_5
static let versionIdentifier: Schema.Version = .init(2, 5, 0)
static var models: [any PersistentModel.Type] {
[AnnotationData.self, Person.self, GroupData.self, History.self]
}
// Keep the old Person model for migration
@Model
final class Person {
@Attribute(.unique) var id: UUID
var name: String
var photo: String
var requirement: String
var statue: Bool
var annotationId: UUID?
var number: Int = 0
init(id: UUID = UUID(), name: String = "", photo: String = "", requirement: String = "", status: Bool = false, annotationId: UUID? = nil, number: Int = 0) {
self.id = id
self.name = name
self.photo = photo
self.requirement = requirement
self.statue = status
self.annotationId = annotationId
self.number = number
}
}
// Add the new GroupData model that mirrors Person
@Model
final class GroupData {
@Attribute(.unique) var id: UUID
var name: String
var photo: String
var requirement: String
var status: Bool
var annotationId: UUID?
var number: Int = 0
init(id: UUID = UUID(), name: String = "", photo: String = "", requirement: String = "", status: Bool = false, annotationId: UUID? = nil, number: Int = 0) {
self.id = id
self.name = name
self.photo = photo
self.requirement = requirement
self.status = status
self.annotationId = annotationId
self.number = number
}
}
}
Migration Plan
static let migrationV2toV2_5 = MigrationStage.custom(
fromVersion: LinkMapV2.self,
toVersion: LinkMapV2_5.self,
willMigrate: { context in
do {
let persons = try context.fetch(FetchDescriptor<LinkMapV2.Person>())
print("=== MIGRATION STARTED ===")
print("Found \(persons.count) Person objects to migrate")
guard !persons.isEmpty else {
print("No Person data requires migration")
return
}
for person in persons {
print("Migrating Person: '\(person.name)' with ID: \(person.id)")
let newGroup = LinkMapV2_5.GroupData(
id: person.id, // Keep the same ID
name: person.name,
photo: person.photo,
requirement: person.requirement,
status: person.statue,
annotationId: person.annotationId,
number: person.number
)
context.insert(newGroup)
print("Inserted new GroupData: '\(newGroup.name)'")
// Don't delete the old Person yet to avoid issues
// context.delete(person)
}
try context.save()
print("=== MIGRATION COMPLETED ===")
print("Successfully migrated \(persons.count) Person objects to GroupData")
} catch {
print("=== MIGRATION ERROR ===")
print("Migration failed with error: \(error)")
}
},
didMigrate: { context in
do {
// Verify migration in didMigrate phase
let groups = try context.fetch(FetchDescriptor<LinkMapV2_5.GroupData>())
let oldPersons = try context.fetch(FetchDescriptor<LinkMapV2_5.Person>())
print("=== MIGRATION VERIFICATION ===")
print("New GroupData count: \(groups.count)")
print("Remaining Person count: \(oldPersons.count)")
// Now delete the old Person objects
for person in oldPersons {
context.delete(person)
}
if !oldPersons.isEmpty {
try context.save()
print("Cleaned up \(oldPersons.count) old Person objects")
}
// Print all migrated groups for debugging
for group in groups {
print("Migrated Group: '\(group.name)', Status: \(group.status), Number: \(group.number)")
}
} catch {
print("Migration verification error: \(error)")
}
}
)
And I've attached console output below:
Console Output
Description:
I'm experiencing a critical issue with SwiftData custom migrations where objects created during migration appear to be inserted successfully but aren't persisted or found by queries after migration completes. The migration logs show objects being created, but subsequent queries return zero results.
Problem Details:
I'm migrating from schema version V2 to V3, which involves:
Renaming Person class to GroupData
Keeping the same data structure but changing the class name
Using a custom migration stage to copy data from old to new schema
Migration Code:
swift
static let migrationV2toV3 = MigrationStage.custom(
fromVersion: LinkMapV2.self,
toVersion: LinkMapV3.self,
willMigrate: { context in
do {
let persons = try context.fetch(FetchDescriptor<LinkMapV2.Person>())
print("Found (persons.count) Person objects to migrate") // ✅ Shows 11 objects
for person in persons {
let newGroup = LinkMapV3.GroupData(
id: person.id, // Same UUID
name: person.name,
// ... other properties
)
context.insert(newGroup)
print("Inserted GroupData: '\(newGroup.name)'") // ✅ Confirms insertion
}
try context.save() // ✅ No error thrown
print("Successfully migrated \(persons.count) objects") // ✅ Confirms save
} catch {
print("Migration error: \(error)")
}
},
didMigrate: { context in
do {
let groups = try context.fetch(FetchDescriptor<LinkMapV3.GroupData>())
print("Final GroupData count: \(groups.count)") // ❌ Shows 0 objects!
} catch {
print("Verification error: \(error)")
}
}
)
Console Output:
text
=== MIGRATION STARTED ===
Found 11 Person objects to migrate
Migrating Person: 'Riverside of pipewall' with ID: 7A08C633-4467-4F52-AF0B-579545BA88D0
Inserted new GroupData: 'Riverside of pipewall'
... (all 11 objects processed) ...
=== MIGRATION COMPLETED ===
Successfully migrated 11 Person objects to GroupData
=== MIGRATION VERIFICATION ===
New GroupData count: 0 // ❌ PROBLEM: No objects found!
What I've Tried:
Multiple context approaches:
Using the provided migration context
Creating a new background context with ModelContext(context.container)
Using context.performAndWait for thread safety
Different save strategies:
Calling try context.save() after insertions
Letting SwiftData handle saving automatically
Multiple save calls at different points
Verification methods:
Checking in didMigrate closure
Checking in app's ContentView after migration completes
Using both @Query and manual FetchDescriptor
Schema variations:
Direct V2→V3 migration
Intermediate V2.5 schema with both classes
Lightweight migration with @Attribute(originalName:)
Current Behavior:
Migration runs without errors
Objects appear to be inserted successfully
context.save() completes without throwing errors
But queries in didMigrate and post-migration return empty results
The objects seem to exist in a temporary state that doesn't persist
Expected Behavior:
Objects created during migration should be persisted and queryable
Post-migration queries should return the migrated objects
Data should be available in the main app after migration completes
Environment:
Xcode 16.0+
iOS 18.0+
SwiftData
Swift 6.0+
Key Questions:
Is there a specific way migration contexts should be handled for data to persist?
Are there known issues with object persistence in custom migrations?
Should we be using a different approach for class renaming migrations?
Is there a way to verify that objects are actually being written to the persistent store?
The migration appears to work perfectly until the verification step, where all created objects seem to vanish. Any guidance would be greatly appreciated!
Additional Context from my investigation:
I've noticed these warning messages during migration that might be relevant:
text
SwiftData.ModelContext: Unbinding from the main queue. This context was instantiated on the main queue but is being used off it.
error: Persistent History (76) has to be truncated due to the following entities being removed: (Person)
This suggests there might be threading or context lifecycle issues affecting persistence.
Let me know if you need any additional information about my setup or migration configuration!
I have SwiftData models containing arrays of Codable structs that worked fine before adding CloudKit capability. I believe they are the reason I started seeing errors after enabling CloudKit.
Example model:
@Model
final class ProtocolMedication {
var times: [SchedulingTime] = [] // SchedulingTime is Codable
// other properties...
}
After enabling CloudKit, I get this error logged to the console:
'NSKeyedUnarchiveFromData' should not be used to for un-archiving and will be removed in a future release
CloudKit Console shows this times data as "plain text" instead of "bplist" format.
Other struct/enum properties display correctly (I think) as "bplist" in CloudKit Console.
The local SwiftData storage handled these arrays fine - this issue only appeared with CloudKit integration.
What's the recommended approach for storing arrays of Codable structs in SwiftData models that sync with CloudKit?
I am using SwiftData for my model. Until Xcode 15 beta 4 I did not have issues. Since beta 5 I am receiving the following red warning multiple times:
'NSKeyedUnarchiveFromData' should not be used to for un-archiving and will be removed in a future release
This seems to be a CoreData warning. However, I am not using CoreData directly. I have no way to change the config of CoreData as used by SwiftData.
My model just uses UUID, Int, String, Double, some of them as optionals or Arrays. I only use one attribute (.unique).
Hi, I'm trying to download the container with SwifData of my App from the iPhone device connect through a cable to my MAC, for debug purpose.
I get an error
The specified file could not be transferred.
Domain: com.apple.dt.CoreDeviceError
Code: 7000
User Info: {
DVTErrorCreationDateKey = "2025-10-30 10:00:38 +0000";
NSURL = "file:///Users/maurizio/Desktop/DatiTRIPBOOK/mm.com.TripBook%202025-10-30%2011:00.28.199.xcappdata/AppData/Library";
}
The specified file could not be transferred.
Domain: com.apple.dt.CoreDeviceError
Code: 7000
User Info: {
NSURL = "file:///Users/maurizio/Desktop/DatiTRIPBOOK/mm.com.TripBook%202025-10-30%2011:00.28.199.xcappdata/AppData/Library";
}
Performing a file system operation failed.
Domain: com.apple.dt.remoteservices.error
Code: 11001
Failure Reason: The file could not be opened for writing.
Failed to open Library/SplashBoard/Snapshots/sceneID:mm.com.TripBook-703D890D-C844-4329-B913-288B5FFB9289/9B937793-D789-43D5-B94C-3FA27A508650 for reading, openat(2) returned POSIX error code 1 (parentParam = 5)
Domain: NSPOSIXErrorDomain
Code: 1
Failure Reason: Operation not permitted
System Information
macOS Version 26.0.1 (Build 25A362)
Xcode 26.0.1 (24229) (Build 17A400)
Timestamp: 2025-10-30T11:00:38+01:00
I'm testing my app before releasing to testers, and my app (both macOS and iOS) is crashing when I perform one operation, but only in the production build.
I have data that loads from a remote source, and can be periodically updated. There is an option to delete all of that data from the iCloud data store, unless the user has modified a record. Each table has a flag to indicate that (userEdited). Here's the function that is crashing:
func deleteCommonData<T:PersistentModel & SDBuddyModel>(_ type: T.Type) throws {
try modelContext.delete(model: T.self, where: #Predicate<T> { !$0.userEdited })
}
Here's one of the calls that results in a crash:
try modelManager.deleteCommonData(Link.self)
Here's the error from iOS Console:
SwiftData/DataUtilities.swift:85: Fatal error: Couldn't find \Link.<computed 0x0000000104b9d208 (Bool)> on Link with fields [SwiftData.Schema.PropertyMetadata(name: "id", keypath: \Link.<computed 0x0000000104b09b44 (String)>, defaultValue: Optional("54EC6602-CA7C-4EC7-AC06-16E7F2E22DE7"), metadata: nil), SwiftData.Schema.PropertyMetadata(name: "name", keypath: \Link.<computed 0x0000000104b09b84 (String)>, defaultValue: Optional(""), metadata: nil), SwiftData.Schema.PropertyMetadata(name: "url", keypath: \Link.<computed 0x0000000104b09bc4 (String)>, defaultValue: Optional(""), metadata: nil), SwiftData.Schema.PropertyMetadata(name: "desc", keypath: \Link.<computed 0x0000000104b09c04 (String)>, defaultValue: Optional(""), metadata: nil), SwiftData.Schema.PropertyMetadata(name: "userEdited", keypath: \Link.<computed 0x0000000104b09664 (Bool)>, defaultValue: Optional(false), metadata: nil), SwiftData.Schema.PropertyMetadata(name: "modified", keypath: \Link.<computed 0x0000000104b09c44 (Date)>, defaultVal<…>
Here's a fragment of the crash log:
Exception Type: EXC_BREAKPOINT (SIGTRAP)
Exception Codes: 0x0000000000000001, 0x000000019373222c
Termination Reason: Namespace SIGNAL, Code 5, Trace/BPT trap: 5
Terminating Process: exc handler [80543]
Thread 0 Crashed:
0 libswiftCore.dylib 0x19373222c _assertionFailure(_:_:file:line:flags:) + 176
1 SwiftData 0x22a222160 0x22a1ad000 + 479584
2 SwiftData 0x22a2709c0 0x22a1ad000 + 801216
3 SwiftData 0x22a221b08 0x22a1ad000 + 477960
4 SwiftData 0x22a27b0ec 0x22a1ad000 + 844012
5 SwiftData 0x22a27b084 0x22a1ad000 + 843908
6 SwiftData 0x22a28182c 0x22a1ad000 + 870444
7 SwiftData 0x22a2809e8 0x22a1ad000 + 866792
8 SwiftData 0x22a285204 0x22a1ad000 + 885252
9 SwiftData 0x22a281c7c 0x22a1ad000 + 871548
10 SwiftData 0x22a27cf6c 0x22a1ad000 + 851820
11 SwiftData 0x22a27cc48 0x22a1ad000 + 851016
12 SwiftData 0x22a27a6b0 0x22a1ad000 + 841392
13 SwiftData 0x22a285b2c 0x22a1ad000 + 887596
14 SwiftData 0x22a285a10 0x22a1ad000 + 887312
15 SwiftData 0x22a285bcc 0x22a1ad000 + 887756
16 SwiftData 0x22a27cf6c 0x22a1ad000 + 851820
17 SwiftData 0x22a27cc48 0x22a1ad000 + 851016
18 SwiftData 0x22a27a6b0 0x22a1ad000 + 841392
19 SwiftData 0x22a27c0d8 0x22a1ad000 + 848088
20 SwiftData 0x22a27a654 0x22a1ad000 + 841300
21 SwiftData 0x22a1be548 0x22a1ad000 + 70984
22 SwiftData 0x22a1cfd64 0x22a1ad000 + 142692
23 SwiftData 0x22a1b9618 0x22a1ad000 + 50712
24 SwiftData 0x22a1d2e8c 0x22a1ad000 + 155276
25 CoreData 0x187fbb568 thunk for @callee_guaranteed () -> (@out A, @error @owned Error) + 28
26 CoreData 0x187fc2300 partial apply for thunk for @callee_guaranteed () -> (@out A, @error @owned Error) + 24
27 CoreData 0x187fc19c4 closure #1 in closure #1 in NSManagedObjectContext._rethrowsHelper_performAndWait<A>(fn:execute:rescue:) + 192
28 CoreData 0x187fbbda8 thunk for @callee_guaranteed @Sendable () -> () + 28
29 CoreData 0x187fbbdd0 thunk for @escaping @callee_guaranteed @Sendable () -> () + 28
30 CoreData 0x187f663fc developerSubmittedBlockToNSManagedObjectContextPerform + 252
31 libdispatch.dylib 0x180336ac4 _dispatch_client_callout + 16
32 libdispatch.dylib 0x18032c940 _dispatch_lane_barrier_sync_invoke_and_complete + 56
33 CoreData 0x187fd7290 -[NSManagedObjectContext performBlockAndWait:] + 364
34 CoreData 0x187fc1fb8 NSManagedObjectContext.performAndWait<A>(_:) + 544
35 SwiftData 0x22a1b877c 0x22a1ad000 + 46972
36 SwiftData 0x22a1be2a8 0x22a1ad000 + 70312
37 SwiftData 0x22a1c0e34 0x22a1ad000 + 81460
38 SwiftData 0x22a23ea94 0x22a1ad000 + 596628
39 SwiftData 0x22a256828 0x22a1ad000 + 694312
40 Sourdough Buddy 0x104e5dc98 specialized ModelManager.deleteCommonData<A>(_:) + 144 (ModelManager.swift:128) [inlined]
41 Sourdough Buddy 0x104e5dc98 closure #1 in SettingsView.clearStarterData.getter + 876 (SettingsView.swift:243)
It works if I do the following instead:
try modelContext.delete(model: Link.self, where: #Predicate { !$0.userEdited })
Why would the func call work in development, but crash in production? And why does doing the more verbose way work instead?
I think this is a bug.
Thanks
I'm using Swift Data for an app that requires iOS 18.
All of my models conform to a protocol that guarantees they have a 'serverID' String variable.
I wrote a function that would allow me to pass in a serverID String and have it fetch the model object that matched. Because I am lazy and don't like writing the same functions over and over, I used a Self reference so that all of my conforming models get this static function.
Imagine my model is called "WhatsNew". Here's some code defining the protocol and the fetching function.
protocol RemotelyFetchable: PersistentModel {
var serverID: String { get }
}
extension WhatsNew: RemotelyFetchable {}
extension RemotelyFetchable {
static func fetchOne(withServerID identifier: String, inContext modelContext: ModelContext) -> Self? {
var fetchDescriptor = FetchDescriptor<Self>()
fetchDescriptor.predicate = #Predicate<Self> { $0.serverID == identifier }
do {
let allModels = try modelContext.fetch(fetchDescriptor)
return allModels.first
} catch {
return nil
}
}
}
Worked great! Or so I thought...
I built this and happily ran a debug build in the Simulator and on devices for months while developing the initial version but when I went to go do a release build for TestFlight, that build reliably crashed on every device with a message like this:
SwiftData/DataUtilities.swift:65: Fatal error: Couldn't find \WhatsNew. on WhatsNew with fields [SwiftData.Schema.PropertyMetadata(name: "serverID", keypath: \WhatsNew., defaultValue: nil, metadata: Optional(Attribute - name: , options: [unique], valueType: Any, defaultValue: nil, hashModifier: nil)), SwiftData.Schema.PropertyMetadata(name: "title", keypath: \WhatsNew., defaultValue: nil, metadata: nil), SwiftData.Schema.PropertyMetadata(name: "bulletPoints", keypath: \WhatsNew.)>, defaultValue: nil, metadata: nil), SwiftData.Schema.PropertyMetadata(name: "dateDescription", keypath: \WhatsNew., defaultValue: nil, metadata: nil), SwiftData.Schema.PropertyMetadata(name: "readAt", keypath: \WhatsNew.)>, defaultValue: nil, metadata: nil)]
It seems (cannot confirm) that something in the release build optimization process is stripping out some metadata / something about these models that makes this predicate crash.
Tested on iOS 18.0 and 18.1 beta.
How can I resolve this? I have two dozen types that conform to this protocol. I could manually specialize this function for every type myself but... ugh.
First the model:
import SwiftData
//Model one: type of contract, i.e. Firm Fixed Price, etc
@Model
final class TypeOfContract {
var contracts: [Contract]
@Attribute(.unique) var typeName: String
@Attribute(.unique) var typeCode: String
var typeDescription: String
init(contracts: [Contract], typeName: String = "", typeCode: String = "", typeDescription: String = "") {
self.contracts = contracts
self.typeName = typeName
self.typeCode = typeCode
self.typeDescription = typeDescription
}
}
//Model two: the Contract
@Model
final class Contract {
var contractType: TypeOfContract?
var costReports: [CostReport]
@Attribute(.unique) var contractNumber: String
@Attribute(.unique) var contractName: String
var startDate: Date
var endDate: Date
var contractValue: Decimal
var contractCompany: String
var contractContact: String
var contactEmail: String
var contactPhone: String
var contractNotes: String
init(contractType: TypeOfContract?, costReports: [CostReport], contractNumber: String = "", contractName: String = "", startDate: Date = .now, endDate: Date = .now, contractValue: Decimal = 0.00, contractCompany: String = "", contractContact: String = "", contactEmail: String = "", contactPhone: String = "", contractNotes: String = "") {
self.contractType = contractType
self.costReports = costReports
self.contractNumber = contractNumber
self.contractName = contractName
self.startDate = startDate
self.endDate = endDate
self.contractValue = contractValue
self.contractCompany = contractCompany
self.contractContact = contractContact
self.contactEmail = contactEmail
self.contactPhone = contactPhone
self.contractNotes = contractNotes
}
}
//Model Three: The Cost Reports
@Model
final class CostReport {
var contract: Contract?
var periodStartDate: Date
var periodEndDate: Date
var bCWP: Double //Budgeted Cost Work Performed
var aCWP: Double //Actual Cost Work Performed
var bCWS: Double //Budgeted Cost Work Scheduled
//Calculated fields
init(contract: Contract?, periodStartDate: Date = .now, periodEndDate: Date = .now, bCWP: Double = 0.0, aCWP: Double = 0.0, bCWS: Double = 0.0) {
self.contract = contract
self.periodStartDate = periodStartDate
self.periodEndDate = periodEndDate
self.bCWP = bCWP
self.aCWP = aCWP
self.bCWS = bCWS
}
}
Now the code for the Picker
```import SwiftUI
import SwiftData
struct EnterNewContract: View {
@Environment(\.modelContext) var modelContext
@Query(sort: \TypeOfContract.typeName) private var typeOfContracts: [TypeOfContract]
@Query private var contracts: [Contract]
@State private var costReports: [CostReport] = []
@State private var contractType: [TypeOfContract]?
@State private var contractNumber: String = ""
@State private var contractName: String = ""
@State private var startDate: Date = Date()
@State private var endDate: Date = Date()
@State private var contractValue: Decimal = 0
@State private var contractCompany: String = ""
@State private var contractContact: String = ""
@State private var contactEmail: String = ""
@State private var contactPhone: String = ""
@State private var contractNotes: String = ""
var body: some View {
Form {
VStack {
Section(header: Text("Enter New Contract")
.foregroundStyle(.green)
.font(.headline)){
Picker("Select a type of contract", selection: $contractType) {Text("Select type").tag(nil as TypeOfContract?)
ForEach(typeOfContracts, id: \.self) { typeOfContracts in
Text(typeOfContracts.typeName) .tag(typeOfContracts as TypeOfContract?)
}
}
TextField("Contract Number", text: $contractNumber)
.frame(width: 800, height: 40)
TextField("Contract Name", text: $contractName)
.frame(width: 800, height: 40)
DatePicker("Contract Start Date", selection: $startDate, displayedComponents: [.date])
DatePicker("Contract End Date", selection: $endDate, displayedComponents: [.date])
}
}
}
}
}
The code works, for the most part. The selection I make from the list does not appear. Instead there is just a shaded empty box . Also, I need to select my selection choice twice before the check mark to appear. To see the choices and my selection I must click on the empty shaded box.
What did I do wrong
Have a data model that sets certain fields as unique. If the user attempts to save a duplicate value, the save fails quietly with no indication to the user that the save failed. The program is on Mac OS 26.0.1
@Environment(\.modelContext) var modelContext
@Query private var typeOfContracts: [TypeOfContract]
@State private var typeName: String = ""
@State private var typeCode: String = ""
@State private var typeDescription: String = ""
@State private var contracts: [Contract] = []
@State private var errorMessage: String? = "Data Entered"
@State private var showAlert: Bool = false
var body: some View {
Form {
Text("Enter New Contract Type")
.font(.largeTitle)
.foregroundStyle(Color(.green))
.multilineTextAlignment(.center)
TextField("Contract Type Name", text: $typeName)
.frame(width: 800, height: 40)
TextField("Contract Type Code", text: $typeCode)
.frame(width: 800, height: 40)
Text("Contract Type Description")
TextEditor(text: $typeDescription)
.frame(width: 800, height: 200)
.scrollContentBackground(.hidden)
.background(Color.teal)
.font(.system(size: 24))
Button(action: {
self.saveContractType()
})
{
Text("Save new contract type")
}
}
}
func saveContractType() {
let typeOfContract = TypeOfContract(contracts: [])
typeOfContract.typeName = typeName
typeOfContract.typeCode = typeCode
typeOfContract.typeDescription = typeDescription
modelContext.insert(typeOfContract)
do {
try modelContext.save()
}catch {
errorMessage = "Error saving data: \(error.localizedDescription)"
}
}
}
I have tried to set alerts but Xcode tells me that the alerts are not in scope
I am attempting to impliment a a Picker that uses SwiftData to fill in the choices. I am missing something because I can get the picker to appear with the proper selections but the picker does not register my choice (no check mark appears and the text in the picker window is blank after I move to the next field.
The model
import Foundation
import SwiftData
//Model one: type of contract, i.e. Firm Fixed Price, etc
@Model
final class TypeOfContract {
var contracts: [Contract]
@Attribute(.unique) var typeName: String
@Attribute(.unique) var typeCode: String
var typeDescription: String
init(contracts: [Contract], typeName: String = "", typeCode: String = "", typeDescription: String = "") {
self.contracts = contracts
self.typeName = typeName
self.typeCode = typeCode
self.typeDescription = typeDescription
}
}
//Model two: the Contract
@Model
final class Contract {
var contractType: TypeOfContract?
var costReports: [CostReport]
@Attribute(.unique) var contractNumber: String
@Attribute(.unique) var contractName: String
var startDate: Date
var endDate: Date
var contractValue: Decimal
var contractCompany: String
var contractContact: String
var contactEmail: String
var contactPhone: String
var contractNotes: String
init(contractType: TypeOfContract? = nil, costReports: [CostReport], contractNumber: String = "", contractName: String = "", startDate: Date = .now, endDate: Date = .now, contractValue: Decimal = 0.00, contractCompany: String = "", contractContact: String = "", contactEmail: String = "", contactPhone: String = "", contractNotes: String = "") {
self.contractType = contractType
self.costReports = costReports
self.contractNumber = contractNumber
self.contractName = contractName
self.startDate = startDate
self.endDate = endDate
self.contractValue = contractValue
self.contractCompany = contractCompany
self.contractContact = contractContact
self.contactEmail = contactEmail
self.contactPhone = contactPhone
self.contractNotes = contractNotes
}
}
//Model Three: The Cost Reports
@Model
final class CostReport {
var contract: Contract?
var periodStartDate: Date
var periodEndDate: Date
var bCWP: Double //Budgeted Cost Work Performed
var aCWP: Double //Actual Cost Work Performed
var bCWS: Double //Budgeted Cost Work Scheduled
//Calculated fields
init(contract: Contract? = nil, periodStartDate: Date = .now, periodEndDate: Date = .now, bCWP: Double = 0.0, aCWP: Double = 0.0, bCWS: Double = 0.0) {
self.contract = contract
self.periodStartDate = periodStartDate
self.periodEndDate = periodEndDate
self.bCWP = bCWP
self.aCWP = aCWP
self.bCWS = bCWS
}
}
The Swift Code for the input form
import SwiftData
struct EnterNewContract: View {
@Environment(\.modelContext) var modelContext
@Query(sort: \TypeOfContract.typeCode) private var typeOfContracts: [TypeOfContract]
@Query private var contracts: [Contract]
@State private var costReports: [CostReport] = []
@State private var contractType: [TypeOfContract] = []
@State private var contractNumber: String = ""
@State private var contractName: String = ""
@State private var startDate: Date = Date()
@State private var endDate: Date = Date()
@State private var contractValue: Decimal = 0
@State private var contractCompany: String = ""
@State private var contractContact: String = ""
@State private var contactEmail: String = ""
@State private var contactPhone: String = ""
@State private var contractNotes: String = ""
var body: some View {
Form {
VStack {
Section(header: Text("Enter New Contract")
.foregroundStyle(.green)
.font(.headline)){
Picker("Select a type of contract", selection: $contractType) {
ForEach(typeOfContracts, id: \.self) { typeOfContracts in
Text(typeOfContracts.typeCode)
.tag(contractType)
}
}
TextField("Contract Number", text: $contractNumber)
.frame(width: 800, height: 40)
TextField("Contract Name", text: $contractName)
.frame(width: 800, height: 40)
DatePicker("Contract Start Date", selection: $startDate, displayedComponents: [.date])
DatePicker("Contract End Date", selection: $endDate, displayedComponents: [.date])
}
}
}
}
}
Hi,
Not sure how to describe my issue best: I am using SwiftData and CloudKit to store my data.
In the past, when I tested my app on different devices, the data would sync between the devices automatically. For whatever reason this has stopped now and the data no longer syncs. No matter what I do, it feels as if all the data is actually stored just locally on each device.
How can I check if the data is actually stored in the cloud and what could be reasons, why its no longer synching between my devices (and yes, I am logged in with the same Apple ID on all devices).
Thanks for any hint!
Max
When deleting a SwiftData entity, I sometimes encounter the following error in a document based SwiftUI app:
Fatal error: Unexpected backing data for snapshot creation: SwiftData._FullFutureBackingData<MyEntityClass>
The deletion happens in a SwiftUI View and the code used to retrieve the entity is standard (the ModelContext is injected from the @Environment):
let myEntity = modelContext.model(for: entityIdToDelete)
modelContext.delete(myEntity)
Unfortunately, I haven't yet managed to isolate this any further in order to come up with a reproducible PoC.
Could you give me further information about what this error means?
I have an app with SwiftData and CloudKit sync enabled, it was working fine but I recently noticed that the sync with CloudKit is not working anymore. All the changes are persisted locally just fine. When running in simulator (iOS 26/iPhone 17 Pro) I get the following error in the console:
CoreData+CloudKit: -[NSCloudKitMirroringDelegate recoverFromError:](2317): <NSCloudKitMirroringDelegate: 0x600003d14c30> - Attempting recovery from error: Error Domain=NSCocoaErrorDomain Code=134421 "Export encountered an unhandled exception while analyzing history in the store." UserInfo={NSLocalizedFailureReason=Export encountered an unhandled exception while analyzing history in the store., NSUnderlyingException=-[NSEntityDescription objectID]: unrecognized selector sent to instance 0x60000351aec0}
I already tried Reseting the environment back to production in CloudKit and Erasing all Contents and Settings in the simulator but I keep getting the same error. Is there something else I can do to fix this?
Hello Apple Developer Forum,
I got the following statement from the AI model. It seems it is also reflecting my real-world experience.
Where do I find an official source that fully describes the array on swiftData model behaviour?
When a SwiftData model contains
an array of value types, such as [String] or [Int],
the array's order is preserved