SwiftData

RSS for tag

Learn to write model code declaratively to add managed persistence and efficient model fetching.

SwiftData Documentation

Posts under SwiftData subtopic

Post

Replies

Boosts

Views

Activity

SwiftData: class inheritance without entity inheritance
In SwiftData, how can I have class inheritance without entity inheritance? My understanding is when models are subclassed they then share the same SQLite table allowing one Query to return multiple model types. However what if we don't require that functionality and only wish to share some overridable logic. I.e. share a base class implementation with multiple @Model subclasses but each model is in it's own SQLite table. E.g. say I want a savedAt timestamp field in every model and have the logic for setting it across all models. Or do some validation that calls super to check parent implementation is valid too. Maybe the validation behaviours can be done using protocols and extensions some how? Thanks!
0
0
41
1d
iOS 27 bug
Hello! I work on Apple's feedback/radar team and am an app developer. However, I'm having trouble with an iOS 27 prototype, as iOS 27 doesn't exist yet at the time of writing, and I'm therefore using a prototype UI version. There's a bug that causes the iOS 18 keyboard to be displayed.
0
0
45
2d
CoreData lightweight migration fails on iOS 26 only — "no such column: Z_110GROUPITEMS1"
We've spent several days diagnosing a CoreData migration crash that is iOS 26-specific and reproducible 100% of the time. Posting here in case others have hit this and because we believe it's an Apple bug worth documenting. Upgrading from our App Store build (CoreData model v10) to our latest TestFlight build (model v11) crashes on iOS 26 with: NSCocoaErrorDomain / Code 134110 no such column: "Z_110GROUPITEMS1" The same upgrade path on iOS 17 and iOS 18 works perfectly. What v10→v11 changes Two new entities added alphabetically early in the alphabet One new optional boolean attribute on an existing entity One new optional to-many relationship on the same existing entity All changes are lightweight-migration compatible. We use shouldMigrateStoreAutomatically = true and shouldInferMappingModelAutomatically = true Here's what we observed Adding two entities alphabetically shifts Z_ENT numbers for all subsequent entities. A central entity (EntityA) moves from Z_ENT 110 (v10) to Z_ENT 112 (v11). It has many-to-many relationships with four other entities (EntityB, EntityC, EntityD, EntityE), all using the same inverse relationship name: groupItems. Because multiple join tables reference EntityA via the same inverse name, CoreData appends a disambiguation suffix (1, 2, etc.) to column names in each join table. In v10, the relevant join tables are Z_110ENTITYB and Z_110ENTITYC, each with a column named Z_110GROUPITEMS + a suffix. -com.apple.CoreData.SQLDebug 3 prints: ALTER TABLE Z_112ENTITYB RENAME COLUMN Z_110GROUPITEMS1 TO Z_112GROUPITEMS1 But the actual column in a fresh iOS 26 v10 store is Z_110GROUPITEMS2. Column not found → crash. iOS 17/18 is consistent: both code paths use suffix 1 for Z_110ENTITYB and 2 for Z_110ENTITYC. Migration succeeds. To confirm We opened the SQLite store from a fresh iOS 26 v10 install and inspected the schema: CREATE TABLE Z_110ENTITYB ( Z_110GROUPITEMS2 INTEGER, Z_112ENTITYB INTEGER, PRIMARY KEY (Z_110GROUPITEMS2, Z_112ENTITYB) ); Then we manually renamed Z_110GROUPITEMS2 → Z_110GROUPITEMS1 and Z_110ENTITYC.Z_110GROUPITEMS1 → Z_110GROUPITEMS2 in the SQLite file. Re-ran the app — migration succeeded. The suffixes are literally swapped between what iOS 26 creates on fresh install vs. what iOS 26's migration engine expects. Our database has over 50 entities and we never before faced such an issue. This is not the first lightweight migration we are releasing after iOS 26 and that's what puzzled us. Why now?
0
0
33
4d
SwiftData @Query with a Custom (non-standard) Sort Criterion
I have a @Query which I would like to sort using a custom criterion. I would like to use an array of SortDescriptors where I can specify a key path and a CUSTOM SortComparator. (I.e., I can write SortComparators which do what I want, but I can't use them in a SortDescriptor because there is no initializer which takes a SortCompartor which is not a String.StandardComparator.) This is not a question about dynamic sorting, which has well-known solutions. I am trying to perform a sort which cannot be satisfied by any existing SortDescriptor (or array of SortDescriptors). Any thoughts about how to resolve this situation?
2
0
67
4d
SwiftData 'simple' migration failing
This is a long post, so let me start with a summary: I am attempting to implement what "ought to be" a simple SwiftData migration, and am receiving the following fatal error from the ModelContainer initializer: NSCocoaErrorDomain Code=134504 "Cannot use staged migration with an unknown model version." The crash occurs both in the Simulator and on a physical device. Both the original schema and the new schema load and run as expected if loaded from scratch — so I conclude the Models are OK; it is the migration from the original schema to the new schema which is the issue. I have reported this as FB22652791 and Technical Incident Case # 19893980. I have two model projects available — one contrived, the other using my actual SwiftData models. Now the Details I am developing a SwiftUI/SwiftData app. I am (currently) using Xcode 26.5-beta-3. I set up an alpha-test build using the following approach: public class DatabaseSchema { public let dbSchema: Schema = Schema([ Model1.self, ... , Model16.self ], version: Schema.Version(0, 9, 0)) public var modelContainer: ModelContainer { let container: ModelContainer let modelConfiguration = ModelConfiguration(schema: dbSchema, isStoredInMemoryOnly: false) do { container = try ModelContainer(for: dbSchema, migrationPlan: nil, configurations: [modelConfiguration]) } catch { fatalError("Failed to creae model conainer") } return container } This defines database version 0.9. For version 1.0, I made three changes to the database: added an attribute of type String to Model2. added three attributes of type [Struct], where Struct conforms to Codable, Equatable and Hashable to Model3, and added a new model (which I'll call Model17) I define two schemas: public enum Schema090: VersionedSchema { public static var versionIdentifier = Schema.Version(0, 9, 0) public static var models: [any PersistentModel.Type] = [ Model1.self, Schema090.Model2.self, Schema090.Model3.self, ... ] } and public enum Schema100: VersionedSchema { public static var versionIdentifier = Schema.Version(1, 0, 0) public static var models: [any PersistentModel.Type] = [ Model1.swift, Schema100.Model2.self, Schema100.Model3.self, ..., Model16.self, Schema100.Model17.self ] } For models that changed, I use the following approach: public typealias Model3 = Schema100.Model3 extension Schema090 { @Model final class Model3 { ... } public init() { ... } } extension Schema100 { @Model final class Model3 { ... <added attributes, initialized> } public init() { ... } } The DatabaseSchema class was modified as follows: public class DatabaseSchema { public let dbSchema: Schema = Schema([ Model1.self, Schema100.Model2.self, Schema100.Model3.self, ... , Model16.self, Schema100.Model17.self ], version: Schema.Version(1, 0, 0)) public var modelContainer: ModelContainer { let container: ModelContainer let modelConfiguration = ModelConfiguration(schema: dbSchema, isStoredInMemoryOnly: false) do { container = try ModelContainer(for: dbSchema, migrationPlan: MigrationPlan.self, configurations: [modelConfiguration]) } catch { fatalError("Failed to creae model conainer") } return container } where the migration plan is the trivial custom migration that makes sure that all added attributes of existing records are properly initialized. enum MigrationPlan: SchemaMigrationPlan { static var schemas: [any VersionedSchema.Type] = [ Schema090.self, Schema100.self ] static var stages: [MigrationStage] = [version090ToVersion100] static let version090ToVersion100 = MigrationStage(fromVersion: Schema090.self, toVersion: Schema100.self, willMigrate: { _ in }, didMigrate: { context in let models = try context.fetch( FetchDescriptor<Schema100.Model3>()) for model in models { < initial the added attributes > { try context.save() }) } This is all simple stuff. Nothing particularly fancy here. But running this code always crashes in the ModelContainer initializer. In my two sample projects, I get two different error messages — in the contrived example, the error message is Code=134110 "An error occurred during persistent store migration." reason=Cannot migrate store in-place: Validation error missing attribute values on mandatory destination attribute, ... and in the sample project that uses my actual data model, I get NSCocoaErrorDomain Code=134504 "Cannot use staged migration with an unknown model version." My Thoughts Since obviously most folks are doing SwiftData migrations without the problems I am experiencing, the obvious possibilities are I'm doing something stupid that I just don't see. There is a problem because the original schema was given a version value of Schema.Version(0, 9, 0). (i.e., major version number was 0) There is a problem because I am adding an attribute of type [Struct] where Struct is Codable, Hashable, and Equatable. I.e., migration isn't working properly with attributes which are stored as their codable representations. Or maybe something else? In any case, any help you can offer would be greatly appreciated.
7
0
642
6d
889 CoreData errors in a SwiftData app of less than 30 lines
I have created a SwiftData iOS app from Paul Hudson's Hacking With Swift series in order to troubleshoot some SwiftData issues I am having in a separate app. I have raised > FB22925785 I have gone back to basics to try and problem solve so I have used the first part of an app of Paul's from [https://www.hackingwithswift.com/quick-start/swiftdata/defining-a-data-model-with-swiftdata] The App is very simple and only contains the following import SwiftData import SwiftUI @main struct iTour_from_scratchApp: App { var body: some Scene { WindowGroup { ContentView() .modelContainer(for: Destination.self) } } } The data is import SwiftData @Model class Destination { var name: String var details: String var date: Date var priority: Int init(name: String, details: String, date: Date, priority: Int) { self.name = name self.details = details self.date = date self.priority = priority } } The view is import SwiftUI struct ContentView: View { var body: some View { VStack { Image(systemName: "globe") .imageScale(.large) .foregroundStyle(.tint) Text("Hello, world!") } .padding() } } #Preview { ContentView() } When I try to run this, I am getting 889 lines of CoreData errors appearing in the Console and they start with CoreData: error: Failed to stat path '/Users/chrissantavy/Library/Developer/CoreSimulator/Devices/913BFD87-5FD8-47B9-AD0C-81238E74E89E/data/Containers/Data/Application/29586FDF-F08D-48E8-AF58-FD7BD5A30525/Library/Application Support/default.store', errno 2 / No such file or directory. CoreData: error: Executing as effective user 501 CoreData: error: Executing as effective user 501 CoreData: error: Sandbox access to file-write-create denied CoreData: error: Sandbox access to file-write-create denied CoreData: error: Failed to statfs file; errno 2 / No such file or directory. CoreData: error: Failed to statfs file; errno 2 / No such file or directory. CoreData: error: Information for file system CoreData: error: Information for file system CoreData: error: --------------------------- CoreData: error: --------------------------- CoreData: error: File system type: 0 CoreData: error: File system type: 0 CoreData: error: File system flags: 0 CoreData: error: File system flags: 0 CoreData: error: Total data blocks: 0 CoreData: error: Total data blocks: 0 CoreData: error: Free data blocks: 0 CoreData: error: Free data blocks: 0 CoreData: error: Free blocks for nonsuperuser: 0 CoreData: error: Free blocks for nonsuperuser: 0 CoreData: error: Total i-nodes: 0 CoreData: error: Total i-nodes: 0 CoreData: error: File system ID: 0, 0 CoreData: error: File system ID: 0, 0 CoreData: error: Free i-nodes: 0 CoreData: error: Free i-nodes: 0 CoreData: error: Owner UID: 0 CoreData: error: Owner UID: 0 CoreData: error: Filesystem type name: CoreData: error: Filesystem type name: CoreData: error: Mount on name: CoreData: error: Mount on name: CoreData: error: Mount from name: CoreData: error: Mount from name: CoreData: error: Failed to stat path '/Users/chrissantavy/Library/Developer/CoreSimulator/Devices/913BFD87-5FD8-47B9-AD0C-81238E74E89E/data/Containers/Data/Application/29586FDF-F08D-48E8-AF58-FD7BD5A30525/Library/Application Support', errno 2 / No such file or directory. CoreData: error: Failed to stat path '/Users/chrissantavy/Library/Developer/CoreSimulator/Devices/913BFD87-5FD8-47B9-AD0C-81238E74E89E/data/Containers/Data/Application/29586FDF-F08D-48E8-AF58-FD7BD5A30525/Library/Application Support', errno 2 / No such file or directory. CoreData: error: Executing as effective user 501 The full list of errors is attached iTour from scratch Part-1 errors.txt
0
0
58
1w
TestFlight build crashes from fetch descriptor
I have a FetchDescriptor that uses starts(with:) which works fine in debug builds but crashes in TestFlight and archive. For background information I'm using iCloud and model inheritance where the property being used in fetch descriptor is defined on the superclass, the fetch descriptor is for the subclass. Implementation: static func fetchDescriptor(nameStartingWith prefix: String) -> FetchDescriptor<ColorAsset> { let predicate = #Predicate<ColorAsset> { asset in asset.name.starts(with: prefix) } return FetchDescriptor<ColorAsset>(predicate: predicate) } @Model public class Asset: Identifiable { // MARK: - Properties var name: String = "" .... } @available(macOS 26.0, *) @Model public class ColorAsset: Asset { ... }
4
1
408
1w
SwiftData crash on new property (Could not cast...)
I have a small example where adding a new property to a persisted Codable struct causes a crash on launch instead of decoding the missing property using its default value. Steps Run this app once and press "Insert Event" to persist data: import SwiftUI import SwiftData @main struct SwiftDataCrash: App { var body: some Scene { WindowGroup { ContentView() } .modelContainer(for: Event.self) } } struct ContentView: View { @Environment(\.modelContext) private var modelContext @Query private var events: [Event] var body: some View { VStack(spacing: 12) { Text("Events: \(events.count)") Button("Insert Event") { let event = Event( recurrence: Recurrence( interval: 1 ) ) modelContext.insert(event) try? modelContext.save() } List(events) { event in Text(String(describing: event.recurrence)) } } .padding() } } @Model final class Event { var recurrence: Recurrence? = nil init(recurrence: Recurrence? = nil) { self.recurrence = recurrence } } struct Recurrence: Codable { var interval: Int // STEP 2: // After first run + inserting an Event, uncomment this and run again. // Expected: old data decodes with default [] // Actual: SwiftData may crash while reading Event.recurrence // // var exceptionDates: [Date] = [] } Then uncomment: var exceptionDates: [Date] = [] and run again without deleting the store. Actual result App crashes on launch with: Could not cast value of type 'Swift.Optional<Any>' to 'Swift.Array<Foundation.Date>' The crash appears to happen inside generated SwiftData persisted-property getter code. Expected result I expected the old persisted Recurrence values to decode with: exceptionDates == [] Is this expected behavior or a SwiftData bug?
2
0
246
1w
Crash when adding large JSON data to SwiftData: Could not cast value of type '__NSCFBoolean' to 'NSString'
Within the app main struct, the SwiftData modelContainer is created by fetching and decoding JSON from remote site. The decoded data is inserted into the modelContext. Immediately thereafter, the app crashes with the error Could not cast value of type '__NSCFBoolean' to 'NSString' . I have run the JSON from the site through JSON lint and it is correctly structured. The JSON data is structured as follows: Overview object which includes a Result object which includes a List Array. Each List object includes a Books Array. I have run the app through AI and the result indicates that there is data corruption when adding the data to the database. The AI rewrote the code such that the book data is encoded into a data blob and then adds the data to the database, instead of adding the individual books (which is extensive.) This approach works without crashing, but I would like to find out if this is indeed a SwiftData issue.
4
0
165
Jul ’25
SwiftData App Crashes only in TestFlight...
I have been building a SwiftUI/SwiftData app for some time that has been working fine in both the simulator and devices I have loaded from Xcode. These include two iPhones an iPad and a VisionPro. I have gotten to the point where I wanted to do some external beta testing so uploaded the App to the AppStore and then had a couple of users download via TestFlight. Unfortunately the App crashes and I have been unable to figure out why based on the feedback that I have gotten. The app has 4 Models that are linked in a fairly straightforward manner. There is a Habit class that is the central object. An Aspiration class that may have several Habits associated with it. An Anchor Class and a Celebration Class both attach to a Habit. I was able to get my neighbor to use TestFlight to download the App and it crashed when trying to insert a Habit but Aspirations, Anchors and Celebrations work fine and can be added, stored and deleted without issue. I then had my neighbor connect their phone to my computer and I download the app directly and it works fine as expected even when not connected to the debugger so clearly something is different between the two environments and I am at a loss so could use someone with good knowledge to help me figure this out.
4
0
186
Jul ’25
How to handle completely adopting SwiftData when you need all the lightweight migrations defined in the xcdatamodeld?
At the end over every "how to adopt SwiftData in a CoreData app" it says, now go ahead and delete the xcdatamodeld files. But my xcdatamodeld contains all the migrations necessary to even support SwiftData in the first place. If I have 10 versions of my CoreData model, and the 10th matches the first version of my SwiftData model... But a user is on the 7th version, and then upgrade to the new app that doesn't contain any xcdatamodeld files.. How are you actually supposed to handle this? I don't want to keep supporting both. I just want to use SwiftData.
0
0
186
Jun ’25
SwiftData superclass prevents usage of ID
New subclassing is a great addition to SwiftData, while trying to utilize the superclass type for selection state I’m seeing the following error: @available(macOS 26.0, *) @Model public class Asset { … } var assetSelection: [Asset.ID] = [] Error: 'ID' is inaccessible due to '@_spi' protection level Replacing the type with a subclassed swift data model of Asset works, but to handle mixed selection and the new .dragContainer modifier I need to be able to use the superclass. Is this intended behavior?
7
0
245
Jun ’25
Add App Group to Existing SwiftData App
I have an existing app that uses SwiftData and now want to add widgets. I added the widget extension, created an App Group to use for the main app target and widget targets and successfully created the widget. However, when testing the updates I often experience data loss - as though the including the widget extension is creating a new instance of modelContainer. Am I missing something to ensure there won't be any data loss when adding the App Group and widget extension? For additional context: I’ve followed the Backyard Birds example code except that it uses a separate app package. My app does not use an external app package, but I am using some elements of the DataGeneration file. My files containing the SwiftData models have Target Memberships for both the main app target and widget extension target. In the TimelineProvider for my widgets, I'm doing the following: let modelContext = ModelContext(DataGeneration.container) init() { DataGeneration.generateAllData(modelContext: modelContext) } My DataGeneration file (simplified) is as follows. When adding the widget target, I sometimes see the log for "Creating instance of DataGeneration". import Foundation import SwiftData @Model class DataGeneration { var requiresInitialization: Bool = true init(requiresInitialization: Bool = true) { self.requiresInitialization = requiresInitialization } private func generateInitialData(modelContext: ModelContext) { if requiresInitialization { let budget = Budget() modelContext.insert(budget) requiresInitialization = false } } private static func instance(with modelContext: ModelContext) -> DataGeneration { if let result = try! modelContext.fetch(FetchDescriptor<DataGeneration>()).first { logger.info("Found instance of DataGeneration") return result } else { logger.info("Creating instance of DataGeneration") let instance = DataGeneration() modelContext.insert(instance) return instance } } static func generateAllData(modelContext: ModelContext) { let instance = instance(with: modelContext) instance.generateInitialData(modelContext: modelContext) } } extension DataGeneration { static let container = try! ModelContainer(for: schema, configurations: [.init(isStoredInMemoryOnly: DataGenerationOptions.inMemoryPersistence)]) static let schema = SwiftData.Schema([ DataGeneration.self, Budget.self ]) }
4
0
374
Jun ’25
How to use SwiftData with MVVM architecture?
Hello all! I'm still fairly new to SwiftData, but have recently integrated it into one of my apps which has been going great. Currently, I have this integrated into my project like so (code simplified for illustration): @main struct MyApp: App { var body: some Scene { WindowGroup { ContentView() } .modelContainer(for: Todo.self) } } struct ContentView: View { @Query(sort: \Todo.date) var todos: [Todo] @Environment(\.modelContext) var moc var body: some View { ... } } In my app, the ContentView struct then also contains business logic in the form of various methods to create and modify entities stored in SwiftData. In order to achieve better separation of concerns and make SwiftTesting the view easier, I'd love to move all this business logic code out into a view model. Unfortunately, I understand that this causes issues due to view models not having access to the SwiftUI environment, making it difficult to inject the model container into a view model and using that model to initialize queries. There are some approaches to this that I found which end up defining another layer on top of SwiftData, but I can see how doing that may result in state syncronization issues between what is stored in SwiftData and the model accessing it. Given that MVVM is so popular and widely used, is there a recommended approach of doing this in a consistent way while still preserving state safety between the SwiftData model and the view model? Thanks for any suggestions! Cheers, Robin
1
0
240
Jun ’25
SwiftData Predicate for optional to-many (as required by CloudKit) relationships crashes
Fails with "to-many key not allowed here" // parent.children?.contains(where: { // $0.name == "Abbiejean" // }) != nil parent.children.flatMap { children in children.contains(where: { $0.name == "Abbijean" }) } == true How are we supposed to query on relationships? This is a huge problem. This is a major limitation blocking migration of CoreData to SwiftData. We can do this with NSPredicate: let moodAnalysis = NSPredicate(format: "ANY moodAnalysis.labels.title == %@", label.description) let stateOfMinds = NSPredicate(format: "SUBQUERY(stateOfMinds, $x, SUBQUERY($x.labels, $y, $y.title == %@).@count > 0).@count > 0", label.description) The accepted answer on stack overflow is: you can't Document says that optionals are allowed in predicates The SwiftData team has made a big show of saying that we can use idiomatic swift for our predicates. But we cannot even filter on relationships when the container is backed by CloudKit... That should be a HUGE warning in the documentation. "For those of you who are considering a costly refactor from CoreData to SwiftData, and are currently using CloudKit, all relationships are mandatory optional arrays, and you can't write predicates on them"
3
0
285
Jun ’25
Is SwiftData missing some APIs?
I was taking a look through SwiftData documentation for any changes coming from WWDC 2025 regarding my previous issues that was left unaddressed… KeyPaths are still not provided in Schema.Attribute as it was with Schema.Relationship. I also don’t see an initializer for HistoryTombstone, making it impossible to set up HistoryDelete protocol from what I can gather. I would appreciate a confirmation that we have been provided everything we need to complete the custom store, because I don’t know if everything I need has been provided or if some APIs have not been opened up. Thank you.
0
0
136
Jun ’25
SwiftData Transient Macro Observability
I have a SwiftData model that includes a transient image, declared as follows: @Transient var image: UIImage? It appears that SwiftData does not track changes to transient properties and so the following view will not update when the image changes from nil to an actual image. ZStack(alignment: .topTrailing) { if let image = item?.image { Image(uiImage: image) } else { ProgressView() } } Ideally, the SwiftData model would still observe changes in transient properties and just not persist them. As such, other code that works with observable objects would work as otherwise expected.
0
0
149
Jun ’25
SwiftData Models not working after updating to macOS 26
Im working on an app which have a lot of diffrent models which are having relationships one to many and so on and on macos Sequoia and Sonoma everything is working but on Tahoe i have this error SwiftData/SchemaProperty.swift:286: Fatal error: Illegal attempt to create a property that's a sequence of a non-codable type (_buffer - _ArrayBuffer). Did you mean to use a transformable attribute? I also use computed properties to perform login on model value change like property name is var name: String{ get:{ self._name} set:{ self._name = $0 } } var _name: String = "" I no where use ArrayBuffer i just use [Double] it its needed
3
1
203
Jun ’25
SwiftData #Predicate in Swift 6 language mode
I'm trying to migrate over to the Swift 6 language mode, but the biggest issue I'm facing is that any use of SwiftData #Predicate or SortDescriptor results in this warning from the compiler: Type 'ReferenceWritableKeyPath<GuruSchemaV2.Rubric, Bool>' does not conform to the 'Sendable' protocol; this is an error in the Swift 6 language mode Here is an example predicate, from a static method on the Rubric type: static func notArchived() -> Predicate<Rubric> { return #Predicate<Rubric> { rubric in !rubric.archived } } And the error highlights line 5 of the expanded macro: Foundation.Predicate<Rubric>({ rubric in PredicateExpressions.build_Negation( PredicateExpressions.build_KeyPath( root: PredicateExpressions.build_Arg(rubric), keyPath: \.archived ) ) }) What is the correct way to reference properties of a model type using #Predicate?
0
1
188
Jun ’25
SwiftData: class inheritance without entity inheritance
In SwiftData, how can I have class inheritance without entity inheritance? My understanding is when models are subclassed they then share the same SQLite table allowing one Query to return multiple model types. However what if we don't require that functionality and only wish to share some overridable logic. I.e. share a base class implementation with multiple @Model subclasses but each model is in it's own SQLite table. E.g. say I want a savedAt timestamp field in every model and have the logic for setting it across all models. Or do some validation that calls super to check parent implementation is valid too. Maybe the validation behaviours can be done using protocols and extensions some how? Thanks!
Replies
0
Boosts
0
Views
41
Activity
1d
iOS 27 bug
Hello! I work on Apple's feedback/radar team and am an app developer. However, I'm having trouble with an iOS 27 prototype, as iOS 27 doesn't exist yet at the time of writing, and I'm therefore using a prototype UI version. There's a bug that causes the iOS 18 keyboard to be displayed.
Replies
0
Boosts
0
Views
45
Activity
2d
CoreData lightweight migration fails on iOS 26 only — "no such column: Z_110GROUPITEMS1"
We've spent several days diagnosing a CoreData migration crash that is iOS 26-specific and reproducible 100% of the time. Posting here in case others have hit this and because we believe it's an Apple bug worth documenting. Upgrading from our App Store build (CoreData model v10) to our latest TestFlight build (model v11) crashes on iOS 26 with: NSCocoaErrorDomain / Code 134110 no such column: "Z_110GROUPITEMS1" The same upgrade path on iOS 17 and iOS 18 works perfectly. What v10→v11 changes Two new entities added alphabetically early in the alphabet One new optional boolean attribute on an existing entity One new optional to-many relationship on the same existing entity All changes are lightweight-migration compatible. We use shouldMigrateStoreAutomatically = true and shouldInferMappingModelAutomatically = true Here's what we observed Adding two entities alphabetically shifts Z_ENT numbers for all subsequent entities. A central entity (EntityA) moves from Z_ENT 110 (v10) to Z_ENT 112 (v11). It has many-to-many relationships with four other entities (EntityB, EntityC, EntityD, EntityE), all using the same inverse relationship name: groupItems. Because multiple join tables reference EntityA via the same inverse name, CoreData appends a disambiguation suffix (1, 2, etc.) to column names in each join table. In v10, the relevant join tables are Z_110ENTITYB and Z_110ENTITYC, each with a column named Z_110GROUPITEMS + a suffix. -com.apple.CoreData.SQLDebug 3 prints: ALTER TABLE Z_112ENTITYB RENAME COLUMN Z_110GROUPITEMS1 TO Z_112GROUPITEMS1 But the actual column in a fresh iOS 26 v10 store is Z_110GROUPITEMS2. Column not found → crash. iOS 17/18 is consistent: both code paths use suffix 1 for Z_110ENTITYB and 2 for Z_110ENTITYC. Migration succeeds. To confirm We opened the SQLite store from a fresh iOS 26 v10 install and inspected the schema: CREATE TABLE Z_110ENTITYB ( Z_110GROUPITEMS2 INTEGER, Z_112ENTITYB INTEGER, PRIMARY KEY (Z_110GROUPITEMS2, Z_112ENTITYB) ); Then we manually renamed Z_110GROUPITEMS2 → Z_110GROUPITEMS1 and Z_110ENTITYC.Z_110GROUPITEMS1 → Z_110GROUPITEMS2 in the SQLite file. Re-ran the app — migration succeeded. The suffixes are literally swapped between what iOS 26 creates on fresh install vs. what iOS 26's migration engine expects. Our database has over 50 entities and we never before faced such an issue. This is not the first lightweight migration we are releasing after iOS 26 and that's what puzzled us. Why now?
Replies
0
Boosts
0
Views
33
Activity
4d
SwiftData @Query with a Custom (non-standard) Sort Criterion
I have a @Query which I would like to sort using a custom criterion. I would like to use an array of SortDescriptors where I can specify a key path and a CUSTOM SortComparator. (I.e., I can write SortComparators which do what I want, but I can't use them in a SortDescriptor because there is no initializer which takes a SortCompartor which is not a String.StandardComparator.) This is not a question about dynamic sorting, which has well-known solutions. I am trying to perform a sort which cannot be satisfied by any existing SortDescriptor (or array of SortDescriptors). Any thoughts about how to resolve this situation?
Replies
2
Boosts
0
Views
67
Activity
4d
SwiftData 'simple' migration failing
This is a long post, so let me start with a summary: I am attempting to implement what "ought to be" a simple SwiftData migration, and am receiving the following fatal error from the ModelContainer initializer: NSCocoaErrorDomain Code=134504 "Cannot use staged migration with an unknown model version." The crash occurs both in the Simulator and on a physical device. Both the original schema and the new schema load and run as expected if loaded from scratch — so I conclude the Models are OK; it is the migration from the original schema to the new schema which is the issue. I have reported this as FB22652791 and Technical Incident Case # 19893980. I have two model projects available — one contrived, the other using my actual SwiftData models. Now the Details I am developing a SwiftUI/SwiftData app. I am (currently) using Xcode 26.5-beta-3. I set up an alpha-test build using the following approach: public class DatabaseSchema { public let dbSchema: Schema = Schema([ Model1.self, ... , Model16.self ], version: Schema.Version(0, 9, 0)) public var modelContainer: ModelContainer { let container: ModelContainer let modelConfiguration = ModelConfiguration(schema: dbSchema, isStoredInMemoryOnly: false) do { container = try ModelContainer(for: dbSchema, migrationPlan: nil, configurations: [modelConfiguration]) } catch { fatalError("Failed to creae model conainer") } return container } This defines database version 0.9. For version 1.0, I made three changes to the database: added an attribute of type String to Model2. added three attributes of type [Struct], where Struct conforms to Codable, Equatable and Hashable to Model3, and added a new model (which I'll call Model17) I define two schemas: public enum Schema090: VersionedSchema { public static var versionIdentifier = Schema.Version(0, 9, 0) public static var models: [any PersistentModel.Type] = [ Model1.self, Schema090.Model2.self, Schema090.Model3.self, ... ] } and public enum Schema100: VersionedSchema { public static var versionIdentifier = Schema.Version(1, 0, 0) public static var models: [any PersistentModel.Type] = [ Model1.swift, Schema100.Model2.self, Schema100.Model3.self, ..., Model16.self, Schema100.Model17.self ] } For models that changed, I use the following approach: public typealias Model3 = Schema100.Model3 extension Schema090 { @Model final class Model3 { ... } public init() { ... } } extension Schema100 { @Model final class Model3 { ... <added attributes, initialized> } public init() { ... } } The DatabaseSchema class was modified as follows: public class DatabaseSchema { public let dbSchema: Schema = Schema([ Model1.self, Schema100.Model2.self, Schema100.Model3.self, ... , Model16.self, Schema100.Model17.self ], version: Schema.Version(1, 0, 0)) public var modelContainer: ModelContainer { let container: ModelContainer let modelConfiguration = ModelConfiguration(schema: dbSchema, isStoredInMemoryOnly: false) do { container = try ModelContainer(for: dbSchema, migrationPlan: MigrationPlan.self, configurations: [modelConfiguration]) } catch { fatalError("Failed to creae model conainer") } return container } where the migration plan is the trivial custom migration that makes sure that all added attributes of existing records are properly initialized. enum MigrationPlan: SchemaMigrationPlan { static var schemas: [any VersionedSchema.Type] = [ Schema090.self, Schema100.self ] static var stages: [MigrationStage] = [version090ToVersion100] static let version090ToVersion100 = MigrationStage(fromVersion: Schema090.self, toVersion: Schema100.self, willMigrate: { _ in }, didMigrate: { context in let models = try context.fetch( FetchDescriptor<Schema100.Model3>()) for model in models { < initial the added attributes > { try context.save() }) } This is all simple stuff. Nothing particularly fancy here. But running this code always crashes in the ModelContainer initializer. In my two sample projects, I get two different error messages — in the contrived example, the error message is Code=134110 "An error occurred during persistent store migration." reason=Cannot migrate store in-place: Validation error missing attribute values on mandatory destination attribute, ... and in the sample project that uses my actual data model, I get NSCocoaErrorDomain Code=134504 "Cannot use staged migration with an unknown model version." My Thoughts Since obviously most folks are doing SwiftData migrations without the problems I am experiencing, the obvious possibilities are I'm doing something stupid that I just don't see. There is a problem because the original schema was given a version value of Schema.Version(0, 9, 0). (i.e., major version number was 0) There is a problem because I am adding an attribute of type [Struct] where Struct is Codable, Hashable, and Equatable. I.e., migration isn't working properly with attributes which are stored as their codable representations. Or maybe something else? In any case, any help you can offer would be greatly appreciated.
Replies
7
Boosts
0
Views
642
Activity
6d
889 CoreData errors in a SwiftData app of less than 30 lines
I have created a SwiftData iOS app from Paul Hudson's Hacking With Swift series in order to troubleshoot some SwiftData issues I am having in a separate app. I have raised > FB22925785 I have gone back to basics to try and problem solve so I have used the first part of an app of Paul's from [https://www.hackingwithswift.com/quick-start/swiftdata/defining-a-data-model-with-swiftdata] The App is very simple and only contains the following import SwiftData import SwiftUI @main struct iTour_from_scratchApp: App { var body: some Scene { WindowGroup { ContentView() .modelContainer(for: Destination.self) } } } The data is import SwiftData @Model class Destination { var name: String var details: String var date: Date var priority: Int init(name: String, details: String, date: Date, priority: Int) { self.name = name self.details = details self.date = date self.priority = priority } } The view is import SwiftUI struct ContentView: View { var body: some View { VStack { Image(systemName: "globe") .imageScale(.large) .foregroundStyle(.tint) Text("Hello, world!") } .padding() } } #Preview { ContentView() } When I try to run this, I am getting 889 lines of CoreData errors appearing in the Console and they start with CoreData: error: Failed to stat path '/Users/chrissantavy/Library/Developer/CoreSimulator/Devices/913BFD87-5FD8-47B9-AD0C-81238E74E89E/data/Containers/Data/Application/29586FDF-F08D-48E8-AF58-FD7BD5A30525/Library/Application Support/default.store', errno 2 / No such file or directory. CoreData: error: Executing as effective user 501 CoreData: error: Executing as effective user 501 CoreData: error: Sandbox access to file-write-create denied CoreData: error: Sandbox access to file-write-create denied CoreData: error: Failed to statfs file; errno 2 / No such file or directory. CoreData: error: Failed to statfs file; errno 2 / No such file or directory. CoreData: error: Information for file system CoreData: error: Information for file system CoreData: error: --------------------------- CoreData: error: --------------------------- CoreData: error: File system type: 0 CoreData: error: File system type: 0 CoreData: error: File system flags: 0 CoreData: error: File system flags: 0 CoreData: error: Total data blocks: 0 CoreData: error: Total data blocks: 0 CoreData: error: Free data blocks: 0 CoreData: error: Free data blocks: 0 CoreData: error: Free blocks for nonsuperuser: 0 CoreData: error: Free blocks for nonsuperuser: 0 CoreData: error: Total i-nodes: 0 CoreData: error: Total i-nodes: 0 CoreData: error: File system ID: 0, 0 CoreData: error: File system ID: 0, 0 CoreData: error: Free i-nodes: 0 CoreData: error: Free i-nodes: 0 CoreData: error: Owner UID: 0 CoreData: error: Owner UID: 0 CoreData: error: Filesystem type name: CoreData: error: Filesystem type name: CoreData: error: Mount on name: CoreData: error: Mount on name: CoreData: error: Mount from name: CoreData: error: Mount from name: CoreData: error: Failed to stat path '/Users/chrissantavy/Library/Developer/CoreSimulator/Devices/913BFD87-5FD8-47B9-AD0C-81238E74E89E/data/Containers/Data/Application/29586FDF-F08D-48E8-AF58-FD7BD5A30525/Library/Application Support', errno 2 / No such file or directory. CoreData: error: Failed to stat path '/Users/chrissantavy/Library/Developer/CoreSimulator/Devices/913BFD87-5FD8-47B9-AD0C-81238E74E89E/data/Containers/Data/Application/29586FDF-F08D-48E8-AF58-FD7BD5A30525/Library/Application Support', errno 2 / No such file or directory. CoreData: error: Executing as effective user 501 The full list of errors is attached iTour from scratch Part-1 errors.txt
Replies
0
Boosts
0
Views
58
Activity
1w
TestFlight build crashes from fetch descriptor
I have a FetchDescriptor that uses starts(with:) which works fine in debug builds but crashes in TestFlight and archive. For background information I'm using iCloud and model inheritance where the property being used in fetch descriptor is defined on the superclass, the fetch descriptor is for the subclass. Implementation: static func fetchDescriptor(nameStartingWith prefix: String) -> FetchDescriptor<ColorAsset> { let predicate = #Predicate<ColorAsset> { asset in asset.name.starts(with: prefix) } return FetchDescriptor<ColorAsset>(predicate: predicate) } @Model public class Asset: Identifiable { // MARK: - Properties var name: String = "" .... } @available(macOS 26.0, *) @Model public class ColorAsset: Asset { ... }
Replies
4
Boosts
1
Views
408
Activity
1w
SwiftData crash on new property (Could not cast...)
I have a small example where adding a new property to a persisted Codable struct causes a crash on launch instead of decoding the missing property using its default value. Steps Run this app once and press "Insert Event" to persist data: import SwiftUI import SwiftData @main struct SwiftDataCrash: App { var body: some Scene { WindowGroup { ContentView() } .modelContainer(for: Event.self) } } struct ContentView: View { @Environment(\.modelContext) private var modelContext @Query private var events: [Event] var body: some View { VStack(spacing: 12) { Text("Events: \(events.count)") Button("Insert Event") { let event = Event( recurrence: Recurrence( interval: 1 ) ) modelContext.insert(event) try? modelContext.save() } List(events) { event in Text(String(describing: event.recurrence)) } } .padding() } } @Model final class Event { var recurrence: Recurrence? = nil init(recurrence: Recurrence? = nil) { self.recurrence = recurrence } } struct Recurrence: Codable { var interval: Int // STEP 2: // After first run + inserting an Event, uncomment this and run again. // Expected: old data decodes with default [] // Actual: SwiftData may crash while reading Event.recurrence // // var exceptionDates: [Date] = [] } Then uncomment: var exceptionDates: [Date] = [] and run again without deleting the store. Actual result App crashes on launch with: Could not cast value of type 'Swift.Optional<Any>' to 'Swift.Array<Foundation.Date>' The crash appears to happen inside generated SwiftData persisted-property getter code. Expected result I expected the old persisted Recurrence values to decode with: exceptionDates == [] Is this expected behavior or a SwiftData bug?
Replies
2
Boosts
0
Views
246
Activity
1w
Crash when adding large JSON data to SwiftData: Could not cast value of type '__NSCFBoolean' to 'NSString'
Within the app main struct, the SwiftData modelContainer is created by fetching and decoding JSON from remote site. The decoded data is inserted into the modelContext. Immediately thereafter, the app crashes with the error Could not cast value of type '__NSCFBoolean' to 'NSString' . I have run the JSON from the site through JSON lint and it is correctly structured. The JSON data is structured as follows: Overview object which includes a Result object which includes a List Array. Each List object includes a Books Array. I have run the app through AI and the result indicates that there is data corruption when adding the data to the database. The AI rewrote the code such that the book data is encoded into a data blob and then adds the data to the database, instead of adding the individual books (which is extensive.) This approach works without crashing, but I would like to find out if this is indeed a SwiftData issue.
Replies
4
Boosts
0
Views
165
Activity
Jul ’25
SwiftData App Crashes only in TestFlight...
I have been building a SwiftUI/SwiftData app for some time that has been working fine in both the simulator and devices I have loaded from Xcode. These include two iPhones an iPad and a VisionPro. I have gotten to the point where I wanted to do some external beta testing so uploaded the App to the AppStore and then had a couple of users download via TestFlight. Unfortunately the App crashes and I have been unable to figure out why based on the feedback that I have gotten. The app has 4 Models that are linked in a fairly straightforward manner. There is a Habit class that is the central object. An Aspiration class that may have several Habits associated with it. An Anchor Class and a Celebration Class both attach to a Habit. I was able to get my neighbor to use TestFlight to download the App and it crashed when trying to insert a Habit but Aspirations, Anchors and Celebrations work fine and can be added, stored and deleted without issue. I then had my neighbor connect their phone to my computer and I download the app directly and it works fine as expected even when not connected to the debugger so clearly something is different between the two environments and I am at a loss so could use someone with good knowledge to help me figure this out.
Replies
4
Boosts
0
Views
186
Activity
Jul ’25
How to handle completely adopting SwiftData when you need all the lightweight migrations defined in the xcdatamodeld?
At the end over every "how to adopt SwiftData in a CoreData app" it says, now go ahead and delete the xcdatamodeld files. But my xcdatamodeld contains all the migrations necessary to even support SwiftData in the first place. If I have 10 versions of my CoreData model, and the 10th matches the first version of my SwiftData model... But a user is on the 7th version, and then upgrade to the new app that doesn't contain any xcdatamodeld files.. How are you actually supposed to handle this? I don't want to keep supporting both. I just want to use SwiftData.
Replies
0
Boosts
0
Views
186
Activity
Jun ’25
SwiftData superclass prevents usage of ID
New subclassing is a great addition to SwiftData, while trying to utilize the superclass type for selection state I’m seeing the following error: @available(macOS 26.0, *) @Model public class Asset { … } var assetSelection: [Asset.ID] = [] Error: 'ID' is inaccessible due to '@_spi' protection level Replacing the type with a subclassed swift data model of Asset works, but to handle mixed selection and the new .dragContainer modifier I need to be able to use the superclass. Is this intended behavior?
Replies
7
Boosts
0
Views
245
Activity
Jun ’25
Add App Group to Existing SwiftData App
I have an existing app that uses SwiftData and now want to add widgets. I added the widget extension, created an App Group to use for the main app target and widget targets and successfully created the widget. However, when testing the updates I often experience data loss - as though the including the widget extension is creating a new instance of modelContainer. Am I missing something to ensure there won't be any data loss when adding the App Group and widget extension? For additional context: I’ve followed the Backyard Birds example code except that it uses a separate app package. My app does not use an external app package, but I am using some elements of the DataGeneration file. My files containing the SwiftData models have Target Memberships for both the main app target and widget extension target. In the TimelineProvider for my widgets, I'm doing the following: let modelContext = ModelContext(DataGeneration.container) init() { DataGeneration.generateAllData(modelContext: modelContext) } My DataGeneration file (simplified) is as follows. When adding the widget target, I sometimes see the log for "Creating instance of DataGeneration". import Foundation import SwiftData @Model class DataGeneration { var requiresInitialization: Bool = true init(requiresInitialization: Bool = true) { self.requiresInitialization = requiresInitialization } private func generateInitialData(modelContext: ModelContext) { if requiresInitialization { let budget = Budget() modelContext.insert(budget) requiresInitialization = false } } private static func instance(with modelContext: ModelContext) -> DataGeneration { if let result = try! modelContext.fetch(FetchDescriptor<DataGeneration>()).first { logger.info("Found instance of DataGeneration") return result } else { logger.info("Creating instance of DataGeneration") let instance = DataGeneration() modelContext.insert(instance) return instance } } static func generateAllData(modelContext: ModelContext) { let instance = instance(with: modelContext) instance.generateInitialData(modelContext: modelContext) } } extension DataGeneration { static let container = try! ModelContainer(for: schema, configurations: [.init(isStoredInMemoryOnly: DataGenerationOptions.inMemoryPersistence)]) static let schema = SwiftData.Schema([ DataGeneration.self, Budget.self ]) }
Replies
4
Boosts
0
Views
374
Activity
Jun ’25
How to use SwiftData with MVVM architecture?
Hello all! I'm still fairly new to SwiftData, but have recently integrated it into one of my apps which has been going great. Currently, I have this integrated into my project like so (code simplified for illustration): @main struct MyApp: App { var body: some Scene { WindowGroup { ContentView() } .modelContainer(for: Todo.self) } } struct ContentView: View { @Query(sort: \Todo.date) var todos: [Todo] @Environment(\.modelContext) var moc var body: some View { ... } } In my app, the ContentView struct then also contains business logic in the form of various methods to create and modify entities stored in SwiftData. In order to achieve better separation of concerns and make SwiftTesting the view easier, I'd love to move all this business logic code out into a view model. Unfortunately, I understand that this causes issues due to view models not having access to the SwiftUI environment, making it difficult to inject the model container into a view model and using that model to initialize queries. There are some approaches to this that I found which end up defining another layer on top of SwiftData, but I can see how doing that may result in state syncronization issues between what is stored in SwiftData and the model accessing it. Given that MVVM is so popular and widely used, is there a recommended approach of doing this in a consistent way while still preserving state safety between the SwiftData model and the view model? Thanks for any suggestions! Cheers, Robin
Replies
1
Boosts
0
Views
240
Activity
Jun ’25
SwiftData Predicate for optional to-many (as required by CloudKit) relationships crashes
Fails with "to-many key not allowed here" // parent.children?.contains(where: { // $0.name == "Abbiejean" // }) != nil parent.children.flatMap { children in children.contains(where: { $0.name == "Abbijean" }) } == true How are we supposed to query on relationships? This is a huge problem. This is a major limitation blocking migration of CoreData to SwiftData. We can do this with NSPredicate: let moodAnalysis = NSPredicate(format: "ANY moodAnalysis.labels.title == %@", label.description) let stateOfMinds = NSPredicate(format: "SUBQUERY(stateOfMinds, $x, SUBQUERY($x.labels, $y, $y.title == %@).@count > 0).@count > 0", label.description) The accepted answer on stack overflow is: you can't Document says that optionals are allowed in predicates The SwiftData team has made a big show of saying that we can use idiomatic swift for our predicates. But we cannot even filter on relationships when the container is backed by CloudKit... That should be a HUGE warning in the documentation. "For those of you who are considering a costly refactor from CoreData to SwiftData, and are currently using CloudKit, all relationships are mandatory optional arrays, and you can't write predicates on them"
Replies
3
Boosts
0
Views
285
Activity
Jun ’25
Is SwiftData missing some APIs?
I was taking a look through SwiftData documentation for any changes coming from WWDC 2025 regarding my previous issues that was left unaddressed… KeyPaths are still not provided in Schema.Attribute as it was with Schema.Relationship. I also don’t see an initializer for HistoryTombstone, making it impossible to set up HistoryDelete protocol from what I can gather. I would appreciate a confirmation that we have been provided everything we need to complete the custom store, because I don’t know if everything I need has been provided or if some APIs have not been opened up. Thank you.
Replies
0
Boosts
0
Views
136
Activity
Jun ’25
SwiftData Transient Macro Observability
I have a SwiftData model that includes a transient image, declared as follows: @Transient var image: UIImage? It appears that SwiftData does not track changes to transient properties and so the following view will not update when the image changes from nil to an actual image. ZStack(alignment: .topTrailing) { if let image = item?.image { Image(uiImage: image) } else { ProgressView() } } Ideally, the SwiftData model would still observe changes in transient properties and just not persist them. As such, other code that works with observable objects would work as otherwise expected.
Replies
0
Boosts
0
Views
149
Activity
Jun ’25
SwiftData Models not working after updating to macOS 26
Im working on an app which have a lot of diffrent models which are having relationships one to many and so on and on macos Sequoia and Sonoma everything is working but on Tahoe i have this error SwiftData/SchemaProperty.swift:286: Fatal error: Illegal attempt to create a property that's a sequence of a non-codable type (_buffer - _ArrayBuffer). Did you mean to use a transformable attribute? I also use computed properties to perform login on model value change like property name is var name: String{ get:{ self._name} set:{ self._name = $0 } } var _name: String = "" I no where use ArrayBuffer i just use [Double] it its needed
Replies
3
Boosts
1
Views
203
Activity
Jun ’25
SwiftData #Predicate in Swift 6 language mode
I'm trying to migrate over to the Swift 6 language mode, but the biggest issue I'm facing is that any use of SwiftData #Predicate or SortDescriptor results in this warning from the compiler: Type 'ReferenceWritableKeyPath<GuruSchemaV2.Rubric, Bool>' does not conform to the 'Sendable' protocol; this is an error in the Swift 6 language mode Here is an example predicate, from a static method on the Rubric type: static func notArchived() -> Predicate<Rubric> { return #Predicate<Rubric> { rubric in !rubric.archived } } And the error highlights line 5 of the expanded macro: Foundation.Predicate<Rubric>({ rubric in PredicateExpressions.build_Negation( PredicateExpressions.build_KeyPath( root: PredicateExpressions.build_Arg(rubric), keyPath: \.archived ) ) }) What is the correct way to reference properties of a model type using #Predicate?
Replies
0
Boosts
1
Views
188
Activity
Jun ’25