SwiftData

RSS for tag

SwiftData 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
Sort by:

Post

Replies

Boosts

Views

Activity

SwiftUI TextField input is super laggy for SwiftData object
have a SwiftUI View where I can edit financial transaction information. The data is stored in SwiftData. If I enter a TextField element and start typing, it is super laggy and there are hangs of 1-2 seconds between each input (identical behaviour if debugger is detached). On the same view I have another TextField that is just attached to a @State variable of that view and TextField updates of that value work flawlessly. So somehow the hangs must be related to my SwiftData object but I cannot figure out why. This used to work fine until a few months ago and then I could see the performance degrading. I have noticed that when I use a placeholder variable like @State private var transactionSubject: String = "" and link that to the TextField, the performance is back to normal. I am then using .onSubmit { self.transaction.subject = self.transactionSubject } to update the value in the end but this again causes a 1 s hang. :/ Below the original code sample with some unnecessary stuff removed: struct EditTransactionView: View { @Environment(\.modelContext) var modelContext @Environment(\.dismiss) var dismiss @State private var testValue: String = "" @Bindable var transaction: Transaction init(transaction: Transaction) { self.transaction = transaction let transactionID = transaction.transactionID let parentTransactionID = transaction.transactionMasterID _childTransactions = Query(filter: #Predicate<Transaction> {item in item.transactionMasterID == transactionID }, sort: \Transaction.date, order: .reverse) _parentTransactions = Query(filter: #Predicate<Transaction> {item in item.transactionID == parentTransactionID }, sort: \Transaction.date, order: .reverse) print(_parentTransactions) } //Function to keep text length in limits func limitText(_ upper: Int) { if self.transaction.icon.count > upper { self.transaction.icon = String(self.transaction.icon.prefix(upper)) } } var body: some View { ZStack { Form{ Section{ //this one hangs TextField("Amount", value: $transaction.amount, format: .currency(code: Locale.current.currency?.identifier ?? "USD")) //this one works perfectly TextField("Test", text: $testValue) HStack{ TextField("Enter subject", text: $transaction.subject) .onAppear(perform: { UITextField.appearance().clearButtonMode = .whileEditing }) Divider() TextField("Select icon", text: $transaction.icon) .keyboardType(.init(rawValue: 124)!) .multilineTextAlignment(.trailing) } } } .onDisappear(){ if transaction.amount == 0 { // modelContext.delete(transaction) } } .onChange(of: selectedItem, loadPhoto) .navigationTitle("Transaction") .navigationBarTitleDisplayMode(.inline) .toolbar{ Button("Cancel", systemImage: "trash"){ modelContext.delete(transaction) dismiss() } } .sheet(isPresented: $showingImagePickerView){ ImagePickerView(isPresented: $showingImagePickerView, image: $image, sourceType: .camera) } .onChange(of: image){ let data = image?.pngData() if !(data?.isEmpty ?? false) { transaction.photo = data } } .onAppear(){ cameraManager.requestPermission() setDefaultVendor() setDefaultCategory() setDefaultGroup() } .sheet(isPresented: $showingAmountEntryView){ AmountEntryView(amount: $transaction.amount) } } } }
1
0
90
2d
Is realtime multidevice persistence possible using SwiftData?
I really enjoyed using SwiftData for persistence until I found out that the CloudKit integration ensures changes are only eventually consistent, and that changes can propagate to other devices after as long as minutes, making it useless for any feature that involves handoff between devices. Devastating news but I guess it’s on me for nrtfm. I may try my hand at a custom model context DataStore integrating Powersync, but that’s a whole trip and before I embark on it I was wondering if anyone had suggestions for resolving this problem in a simple and elegant manager that allows me to keep as much of the machinery within Apple’s ecosystem as possible, while ensure reliable “live” updates to SwiftData stores on all eligible devices.
2
0
154
3d
SwiftData ModelContext.insert crashes, why?
This simple test fails in my project. Similar code in my application also crashes. How do I debug the problem? What project settings are required. I have added SwiftData as a framework to test (and application) targets? Thanks, The problem is with: modelContext.insert(item) Thread 1: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0) import XCTest import SwiftData @Model class FakeModel { var name: String init(name: String) { self.name = name } } @MainActor final class FakeModelTests: XCTestCase { var modelContext: ModelContext! override func setUp() { super.setUp() do { let container = try ModelContainer(for: FakeModel.self, configurations: ModelConfiguration(isStoredInMemoryOnly: true)) modelContext = container.mainContext } catch { XCTFail("Failed to create ModelContainer: \(error)") modelContext = nil } } func testSaveFetchDeleteFakeItem() { guard let modelContext = modelContext else { XCTFail("ModelContext must be initialized") return } let item = FakeModel(name: "Test") modelContext.insert(item) let fetchDescriptor = FetchDescriptor<FakeModel>() let items = try! modelContext.fetch(fetchDescriptor) XCTAssertEqual(items.count, 1) XCTAssertEqual(items.first?.name, "Test") modelContext.delete(item) let itemsAfterDelete = try! modelContext.fetch(fetchDescriptor) XCTAssertEqual(itemsAfterDelete.count, 0) } }
4
0
134
5d
SwiftData Inheritance Query Specialized Model
Hi, I am currently experiencing some trouble when using parent model property in a predicate of a child model. I have an Item class that define parent-child relationship: @Model class Item { var timestamp: Date @Relationship(inverse: \Item.children) var parent: Item? var children: [Item] init(parent: Item? = nil, children: [Item] = [], timestamp: Date = .now) { self.parent = parent self.children = children self.timestamp = timestamp } } I subclass this model like that: @available(iOS 26, *) @Model final class CollectionItem: Item { /* ... */ } When i make a Query in my View like that the system crashes: @Query( filter: #Predicate<CollectionItem> { $0.parent == nil }, sort: \CollectionItem.name, ) private var collections: [CollectionItem] CrashReportError: Fatal Error in DataUtilities.swift AppName crashed due to fatalError in DataUtilities.swift at line 85. Couldn't find \CollectionItem.<computed 0x000000034005d4e8 (Optional<Item>)> on CollectionItem with fields [SwiftData.Schema.PropertyMetadata(name: "name", keypath: \CollectionItem.<computed 0x000000034003c120 (String)>, defaultValue: nil, metadata: nil), SwiftData.Schema.PropertyMetadata(name: "icon", keypath: \CollectionItem.<computed 0x000000034003ca04 (Optional<String>)>, defaultValue: nil, metadata: nil), SwiftData.Schema.PropertyMetadata(name: "timestamp", keypath: \Item.<computed 0x0000000340048018 (Date)>, defaultValue: nil, metadata: nil), SwiftData.Schema.PropertyMetadata(name: "parent", keypath: \Item.<computed 0x0000000340048a4c (Optional<Item>)>, defaultValue: nil, metadata: Optional(Relationship - name: , options: [], valueType: Any, destination: , inverseName: nil, inverseKeypath: Optional(\Item.<computed 0x0000000340048fe8 (Array<Item>)>))), SwiftData.Schema.PropertyMetadata(name: "children", keypath: \Item.<computed 0x0000000340048fe8 (Array<Item>)>, defaultValue: nil, metadata: nil)] When I query as Item it works but then i cannot sort on CollectionItem field and must add unnecessary down casting: @Query( filter: #Predicate<Item> { $0.parent == nil && $0 is CollectionItem }, ) private var items: [Item] Am I missing something? Is it a platform limitation or a known issue?
9
0
188
2d
How do you observe the count of records in a Swift Data relationship?
What is the correct way to track the number of items in a relationship using SwiftData and SwiftUI? Imagine a macOS application with a sidebar that lists Folders and Tags. An Item can belong to a Folder and have many Tags. In the sidebar, I want to show the name of the Folder or Tag along with the number of Items in it. I feel like I'm missing something obvious within SwiftData to wire this up such that my SwiftUI views correctly updated whenever the underlying modelContext is updated. // The basic schema @Model final class Item { var name = "Untitled Item" var folder: Folder? = nil var tags: [Tag] = [] } @Model final class Folder { var name = "Untitled Folder" var items: [Item] = [] } @Model final class Tag { var name = "Untitled Tag" var items: [Item] = [] } // A SwiftUI view to show a Folder. struct FolderRowView: View { let folder: Folder // Should I use an @Query here?? // @Query var items: [Item] var body: some View { HStack { Text(folder.name) Spacer() Text(folder.items.count.formatted()) } } } The above code works, once, but if I then add a new Item to that Folder, then this SwiftUI view does not update. I can make it work if I use an @Query with an #Predicate but even then I'm not quite sure how the #Predicate is supposed to be written. (And it seems excessive to have an @Query on every single row, given how many there could be.) struct FolderView: View { @Query private var items: [Item] private var folder: Folder init(folder: Folder) { self.folder = folder // I've read online that this needs to be captured outside the Predicate? let identifier = folder.persistentModelID _items = Query(filter: #Predicate { link in // Is this syntax correct? The results seem inconsistent in my app... if let folder = link.folder { return folder.persistentModelID == identifier } else { return false } }) } var body: some View { HStack { Text(folder.name) Spacer() // This mostly works. Text(links.count.formatted()) } } } As I try to integrate SwiftData and SwiftUI into a traditional macOS app with a sidebar, content view and inspector I'm finding it challenging to understand how to wire everything up. In this particular example, tracking the count, is there a "correct" way to handle this?
1
0
99
5d
SwiftData Fatal error: Editors must register their identifiers before invoking operations on this store
I have a UIKit app where I've adopted SwiftData and I'm struggling with a crash coming in from some of my users. I'm not able to reproduce it myself and as it only happens to a small fraction of my user base, it seems like a race condition of some sort. This is the assertion message: SwiftData/DefaultStore.swift:453: Fatal error: API Contract Violation: Editors must register their identifiers before invoking operations on this store SwiftData.DefaultStore: 00CF060A-291A-4E79-BEC3-E6A6B20F345E did not. (ID is unique per crash) This is the ModelActor that crashes: @available(iOS 17, *) @ModelActor actor ConsumptionDatabaseStorage: ConsumptionSessionStorage { struct Error: LocalizedError { var errorDescription: String? } private let sortDescriptor = [SortDescriptor(\SDConsumptionSession.startTimeUtc, order: .reverse)] static func createStorage(userId: String) throws -> ConsumptionDatabaseStorage { guard let appGroupContainer = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: UserDefaults.defaultAppGroupIdentifier) else { throw Error(errorDescription: "Invalid app group container ID") } func createModelContainer(databaseUrl: URL) throws -> ModelContainer { return try ModelContainer(for: SDConsumptionSession.self, SDPriceSegment.self, configurations: ModelConfiguration(url: databaseUrl)) } let databaseUrl = appGroupContainer.appendingPathComponent("\(userId).sqlite") do { return self.init(modelContainer: try createModelContainer(databaseUrl: databaseUrl)) } catch { // Creating the model storage failed. Remove the database file and try again. try? FileManager.default.removeItem(at: databaseUrl) return self.init(modelContainer: try createModelContainer(databaseUrl: databaseUrl)) } } func isStorageEmpty() async -> Bool { (try? self.modelContext.fetchCount(FetchDescriptor<SDConsumptionSession>())) ?? 0 == 0 // <-- Crash here! } func sessionsIn(interval: DateInterval) async throws -> [ConsumptionSession] { let fetchDescriptor = FetchDescriptor(predicate: #Predicate<SDConsumptionSession> { sdSession in if let startDate = sdSession.startTimeUtc { return interval.start <= startDate && interval.end > startDate } else { return false } }, sortBy: self.sortDescriptor) let consumptionSessions = try self.modelContext.fetch(fetchDescriptor) // <-- Crash here! return consumptionSessions.map { ConsumptionSession(swiftDataSession: $0) } } func updateSessions(sessions: [ConsumptionSession]) async throws { if #unavailable(iOS 18) { // Price segments are duplicated if re-inserted so unfortunately we have to delete and reinsert sessions. // On iOS 18, this is enforced by the #Unique macro on SDPriceSegment. let sessionIds = Set(sessions.map(\.id)) try self.modelContext.delete(model: SDConsumptionSession.self, where: #Predicate<SDConsumptionSession> { sessionIds.contains($0.id) }) } for session in sessions { self.modelContext.insert(SDConsumptionSession(consumptionSession: session)) } if self.modelContext.hasChanges { try self.modelContext.save() } } func deleteAllSessions() async { if #available(iOS 18, *) { try? self.modelContainer.erase() } else { self.modelContainer.deleteAllData() } } } The actor conforms to this protocol: protocol ConsumptionSessionStorage { func isStorageEmpty() async -> Bool func hasCreditCardSessions() async -> Bool func sessionsIn(interval: DateInterval) async throws -> [ConsumptionSession] func updateSessions(sessions: [ConsumptionSession]) async throws func deleteAllSessions() async } The crash is coming in from line 30 and 41, in other words, when trying to fetch data from the database. There doesn't seem to be any common trait for the crashes. They occur across iOS versions and device types. Any idea what might cause this?
4
0
131
1w
Should ModelActor be used to populate a view?
I'm working with SwiftData and SwiftUI and it's not clear to me if it is good practice to have a @ModelActor directly populate a SwiftUI view. For example when having to combine manual lab results and clinial results from HealthKit. The Clinical lab results are an async operation: @ModelActor actor LabResultsManager { func fetchLabResultsWithHealthKit() async throws -> [LabResultDto] { let manualEntries = try modelContext.fetch(FetchDescriptor<LabResult>()) let clinicalLabs = (try? await HealthKitService.getLabResults()) ?? [] return (manualEntries + clinicalLabs).sorted { $0.date > $1.date }.map { return LabResultDto(from: $0) } } } struct ContentView: View { @State private var labResults: [LabResultDto] = [] var body: some View { List(labResults, id: \.id) { result in VStack(alignment: .leading) { Text(result.testName) Text(result.date, style: .date) } } .task { do { let labManager = LabResultsManager() labResults = try await labManager.fetchLabResultsWithHealthKit() } catch { // Handle error } } } } EDIT: I have a few views that would want to use these labResults so I need an implementation that can be reused. Having to fetch and combine in each view will not be good practice. Can I pass a modelContext to a viewModel?
4
0
134
1w
SwiftData initializing Optional Array to Empty Array
I've been seeing something that I find odd when using two SwiftData models where if I have one model (book, in this case) that has an optional array of another model (page, in this case), the optional array starts out as set to nil, but after about 20 seconds it updates to being an empty array. I see it in Previews and after building. Is this expected behavior? Should I just assume that if there is an optional array in my model it will eventually be initialized to an empty array? Code is below. import SwiftUI import SwiftData @Model final class Book { var title: String = "New Book" @Relationship var pages: [Page]? = nil init(title: String) { self.title = title } } @Model final class Page { var content: String = "Page Content" var book: Book? = nil init() { } } struct ContentView: View { @Environment(\.modelContext) private var modelContext @Query private var books: [Book] var body: some View { NavigationSplitView { List { ForEach(books) { book in NavigationLink { Text("\(book.title)") Text(book.pages?.debugDescription ?? "pages is nil") } label: { Text("\(book.title)") Spacer() Text("\(book.pages?.count.description ?? "pages is nil" )") } } } HStack { Button("Clear Data") { clearData() } Button("Add Book") { addBook() } } .navigationSplitViewColumnWidth(min: 180, ideal: 200) } detail: { Text("Select an item") } } private func clearData() { for book in books { modelContext.delete(book) } try? modelContext.save() } private func addBook() { let newBook = Book(title: "A New Book") modelContext.insert(newBook) } } @main struct BookPageApp: App { var sharedModelContainer: ModelContainer = { let schema = Schema([Book.self, Page.self]) let modelConfiguration = ModelConfiguration(schema: schema, isStoredInMemoryOnly: false) do { return try ModelContainer(for: schema, configurations: [modelConfiguration]) } catch { fatalError("Could not create ModelContainer: \(error)") } }() var body: some Scene { WindowGroup { ContentView() } .modelContainer(sharedModelContainer) } } #Preview { ContentView() .modelContainer(for: Book.self, inMemory: true) }
1
0
82
1w
SwiftData crash when switching between Window and ImmersiveSpace in visionOS
Environment visionOS 26 Xcode 26 Issue I am experiencing crash when trying to access a [String] from a @Model data, after dismissing an immersiveSpace and opening a WindowGroup. This crash only occurs when trying to access the [String] property of my Model. It works fine with other properties. Thread 1: Fatal error: This backing data was detached from a context without resolving attribute faults: PersistentIdentifier(...) Steps to Reproduce Open WindowGroup Dismiss window, open ImmersiveSpace Dismiss ImmersiveSpace, reopen WindowGroup Any guidance would be appreciated! @main struct MyApp: App { var body: some Scene { WindowGroup(id: "main") { ContentView() } .modelContainer(for: [Item.self]) ImmersiveSpace(id: "immersive") { ImmersiveView() } } } // In SwiftData model @Model class Item { var title: String = "" // Accessing this property works fine var tags: [String] = [] @storageRestrictions(accesses: _$backingData, initializes: _tags) init(initialValue) { _$backingData.setValue(forKey: \. tags, to: initialValue) _tags =_ SwiftDataNoType() } get { _$observationRegistrar.access(self, keyPath: \.tags) **return self getValue(forkey: \.tags)** // Crashes here }
3
0
96
1w
Mixing in-memory and persistent SwiftData containers in a Document-based App?
Hello, I'm trying to work on an iPadOS and macOS app that will rely on the document-based system to create some kind of orientation task to follow. Let say task1.myfile will be a check point regulation from NYC to SF and task2.myfile will be a visit as many key location as you can in SF. The file represent the specific landmark location and rules of the game. And once open, I will be able to read KML/GPS file to evaluate their score based with the current task. But opened GPS files does not have to be stored in the task file itself, it stay alongside. I wanted to use that scenario to experiment with SwiftData (I'm a long time CoreData user, I even wrote my own WebDAV based persistent store back in the day), and so, mix both on file and in memory persistent store, with distribution based on object class. With CoreData it would have been possible, but I do not see how to achieve that with SwiftData and DocumentGroup integration. Any idea how to do that?
1
0
81
1w
DocumentBrowser toolbar behavior in SwiftUI apps
I’m building a document-based SwiftData app (iPhone/iPad/Mac). Here’s a minimal example of how I’m using DocumentGroup. DocumentGroup(editing: Trip.self, contentType: .trips) { ContentView() } if #available(iOS 18.0, *) { DocumentGroupLaunchScene { NewDocumentButton("New Trip") } } I’m struggling with the toolbar behavior in DocumentGroup apps. My content view uses a TabView, and each tab contains a NavigationSplitView. After I select a document in the document browser, I see my tabs. Regardless of which tab is selected, there’s a navigation bar showing the document name and a back button to the document browser. However, only the first tab shows the disclosure button to rename the document. I’d expect to be able to rename the document anywhere the name is shown. When I navigate to the detail view of my NavigationSplitView (or when using NavigationView/NavigationStack), I still see that back button to the document browser. When the user taps it, they expect to go back to the previous view, not to the document browser. What’s really odd is that even sheet or fullScreenCover presentations include these document UI elements in the navigation bar. I can’t get rid of them. Even if I set a title via the toolbar or navigationTitle, the rename disclosure button remains visible. Do DocumentGroup apps intentionally show their specific navigation bar everywhere? Is this a bug or expected behavior? And is it expected that the rename disclosure button appears only on the first tab of a TabView?
4
0
140
1w
How to get PersistentIdentifier from a model created in a transaction?
I have a ModelActor that creates a hierarchy of models and returns a PersistentIdentifier for the root. I'd like to do that in a transaction, but I don't know of a good method of getting that identifier if the models are created in a transaction. For instance, an overly simple example: func createItem(timestamp: Date) throws -> PersistentIdentifier { try modelContext.transaction { let item = Item(timestamp: timestamp) modelContext.insert(item) } // how to return item.persistentModelID? } I can't return the item.persistentModelID from the transaction closure and even if I could, it will be a temporary ID until after the transaction is executed. I can't create the Item outside the transaction and just have the transaction do an insert because swift will raise a data race error if you then try to return item.persistentModelID. Is there any way to do this besides a modelContext.fetch* with separate unique identifiers?
2
0
145
1w
CloudKit Sharing Not Working with Other Apple IDs (SwiftData + SwiftUI)
Hi everyone, I’m currently developing a SwiftUI app that uses SwiftData with CloudKit sharing enabled. The app works fine on my own Apple ID, and local syncing with iCloud is functioning correctly — but sharing with other Apple IDs consistently fails. Setup: SwiftUI + SwiftData using a ModelContainer with .shared configuration Sharing UI is handled via UICloudSharingController iCloud container: iCloud.com.de.SkerskiDev.FoodGuard Proper entitlements enabled (com.apple.developer.icloud-services, CloudKit, com.apple.developer.coredata.cloudkit.containers, etc.) Automatic provisioning profiles created by Xcode Error:<CKError 0x1143a2be0: "Bad Container" (5/1014); "Couldn't get container configuration from the server for container iCloud.com.de.SkerskiDev.FoodGuard"> What I’ve tried: Verified the iCloud container is correctly created and enabled in the Apple Developer portal Checked bundle identifier and container settings Rebuilt and reinstalled the app Ensured correct iCloud entitlements and signing capabilities Questions: Why does CloudKit reject the container for sharing while local syncing works fine? Are there known issues with SwiftData .shared containers and multi-user sharing? Are additional steps required (App Store Connect, privacy settings) to allow sharing with other Apple IDs? Any advice, experience, or example projects would be greatly appreciated. 🙏 Thanks! Sebastian
4
0
124
Jul ’25
Change to SwiftData ModelContainer causing crashes
I have some models in my app: [SDPlanBrief.self, SDAirport.self, SDChart.self, SDIndividualRunwayAirport.self, SDLocationBrief.self] SDLocationBrief has a @Relationship with SDChart When I went live with my app I didn't have a versioned schema, but quickly had to change that as I needed to add items to my SDPlanBrief Model. The first versioned schema I made included only the model that I had made a change to. static var models: [any PersistentModel.Type] { [SDPlanBrief.self] } I had made zero changes to my model container and the whole time, and it was working fine. The migration worked well and this is what I was using: .modelContainer(for: [SDAirport.self, SDIndividualRunwayAirport.self, SDLocationBrief.self, SDChart.self, SDPlanBrief.self]) I then saw that to do this all properly, I should actually include ALL of my @Models in the versioned schema: enum AllSwiftDataSchemaV3: VersionedSchema { static var models: [any PersistentModel.Type] { [SDPlanBrief.self, SDAirport.self, SDChart.self, SDIndividualRunwayAirport.self, SDLocationBrief.self] } static var versionIdentifier: Schema.Version = .init(2, 0, 0) } extension AllSwiftDataSchemaV3 { @Model class SDPlanBrief { var destination: String etc... init(destination: String, etc...) { self.destination = destination etc... } } @Model class SDAirport { var catABMinima: String etc... init(catABMinima: String etc...) { self.catABMinima = catABMinima etc... } } @Model class SDChart: Identifiable { var key: String etc... var brief: SDLocationBrief? // @Relationship with SDChart init(key: String etc...) { self.key = key etc... } } @Model class SDIndividualRunwayAirport { var icaoCode: String etc... init(icaoCode: String etc...) { self.icaoCode = icaoCode etc... } } @Model class SDLocationBrief: Identifiable { var briefString: String etc... @Relationship(deleteRule: .cascade, inverse: \SDChart.brief) var chartsArray = [SDChart]() init( briefString: String, etc... chartsArray: [SDChart] = [] ) { self.briefString = briefString etc... self.chartsArray = chartsArray } } } This is ALL my models in here btw. I saw also that modelContainer needed updating to work better for versioned schemas. I changed my modelContainer to look like this: actor ModelContainerActor { @MainActor static func container() -> ModelContainer { let schema = Schema( versionedSchema: AllSwiftDataSchemaV3.self ) let configuration = ModelConfiguration() let container = try! ModelContainer( for: schema, migrationPlan: PlanBriefMigrationPlan.self, configurations: configuration ) return container } } and I am passing in like so: .modelContainer(ModelContainerActor.container()) Each time I run the app now, I suddenly get this message a few times in a row: CoreData: error: Attempting to retrieve an NSManagedObjectModel version checksum while the model is still editable. This may result in an unstable verison checksum. Add model to NSPersistentStoreCoordinator and try again. I typealias all of these models too for the most recent V3 version eg: typealias SDPlanBrief = AllSwiftDataSchemaV3.SDPlanBrief Can someone see if I am doing something wrong here? It seems my TestFlight users are experiencing a crash every now and then when certain views load (I assume when accessing @Query objects). Seems its more so when a view loads quickly, like when removing a subscription view where the data may not have had time to load??? Can someone please have a look and help me out.
6
0
197
Jul ’25
SwiftData and discarding unsaved changes idea???
Someone smarter than me please tell me if this will work... I want to have an edit screen for a SwiftData class. Auto Save is on, but I want to be able to revert changes. I have read all about sending a copy in, sending an ID and creating a new context without autosave, etc. What about simply creating a second set of ephemeral values in the actual original model. initialize them with the actual fields. Edit them and if you save changes, migrate that back to the permanent fields before returning. Don't have to manage a list of @State variables corresponding to every model field, and don't have to worry about a second model context. Anyone have any idea of the memory / performance implications of doing it this way, and if it is even possible? Does this just make a not quite simple situation even more complicated? Haven't tried yet, just got inspiration from reading some medium content on attributes on my lunch break, and wondering if I am just silly for considering it.
2
0
144
Jul ’25
SwiftData SortDescriptor Limitation...
I built a SwiftData App that relies on CloudKit to synchronize data across devices. That means all model relationships must be expressed as Optional. That’s fine, but there is a limitation in using Optional’s in SwiftData SortDescriptors (Crashes App) That means I can’t apply a SortDescriptor to ModelA using some property value in ModelB (even if ModelB must exist) I tried using a computed property in ModelA that referred to the property in ModelB, BUT THIS DOESN”T WORK EITHER! Am I stuck storing redundant data In ModelA just to sort ModelA as I would like???
4
0
142
3w
SwiftData error: Attempting to retrieve an NSManagedObjectModel version checksum while the model is still editable
Hi, I'm getting a very odd error log in my SwiftData setup for an iOS app. It is implemented to support schema migration. When starting the app, it simply prints the following log twice (seems to be dependent on how many migration steps, I have two steps in my sample code): CoreData: error: Attempting to retrieve an NSManagedObjectModel version checksum while the model is still editable. This may result in an unstable verison checksum. Add model to NSPersistentStoreCoordinator and try again. (Yes there is a mistyped word "verison", this is exactly the log) The code actually fully works. But I have neither CloudKit configured, nor is this app in Production yet. I'm still just developing. Here is the setup and code to reproduce the issue. Development mac version: macOS 15.5 XCode version: 16.4 iOS Simulator version: 18.5 Real iPhone version: 18.5 Project name: SwiftDataDebugApp SwiftDataDebugApp.swift: import SwiftUI import SwiftData @main struct SwiftDataDebugApp: App { var sharedModelContainer: ModelContainer = { let schema = Schema([ Item.self, ]) let modelConfiguration = ModelConfiguration(schema: schema, isStoredInMemoryOnly: false, allowsSave: true) do { return try ModelContainer(for: schema, migrationPlan: ModelMigraitonPlan.self, configurations: [modelConfiguration]) } catch { fatalError("Could not create ModelContainer: \(error)") } }() var body: some Scene { WindowGroup { ContentView() } .modelContainer(sharedModelContainer) } } Item.swift: import Foundation import SwiftData typealias Item = ModelSchemaV2_0_0.Item enum ModelSchemaV1_0_0: VersionedSchema { static var versionIdentifier = Schema.Version(1, 0, 0) static var models: [any PersistentModel.Type] { [Item.self] } @Model final class Item { var timestamp: Date init(timestamp: Date) { self.timestamp = timestamp } } } enum ModelSchemaV2_0_0: VersionedSchema { static var versionIdentifier = Schema.Version(2, 0, 0) static var models: [any PersistentModel.Type] { [Item.self] } @Model final class Item { var timestamp: Date var tags: [Tag] = [] init(timestamp: Date, tags: [Tag]) { self.timestamp = timestamp self.tags = tags } } } enum ModelMigraitonPlan: SchemaMigrationPlan { static var schemas: [any VersionedSchema.Type] { [ModelSchemaV1_0_0.self] } static var stages: [MigrationStage] { [migrationV1_0_0toV2_0_0] } static let migrationV1_0_0toV2_0_0 = MigrationStage.custom( fromVersion: ModelSchemaV1_0_0.self, toVersion: ModelSchemaV2_0_0.self, willMigrate: nil, didMigrate: { context in let items = try context.fetch(FetchDescriptor<ModelSchemaV2_0_0.Item>()) for item in items { item.tags = Array(repeating: "abc", count: Int.random(in: 0...3)).map({ Tag(value: $0) }) } try context.save() } ) } Tag.swift: import Foundation struct Tag: Codable, Hashable, Comparable { var value: String init(value: String) { self.value = value } static func < (lhs: Tag, rhs: Tag) -> Bool { return lhs.value < rhs.value } static func == (lhs: Tag, rhs: Tag) -> Bool { return lhs.value == rhs.value } func hash(into hasher: inout Hasher) { hasher.combine(value) } } ContentView.swift: import SwiftUI import SwiftData struct ContentView: View { @Environment(\.modelContext) private var modelContext @Query private var items: [Item] var body: some View { VStack { List { ForEach(items) { item in VStack(alignment: .leading) { Text(item.timestamp, format: Date.FormatStyle(date: .numeric, time: .standard)) HStack { ForEach(item.tags, id: \.hashValue) { tag in Text("\(tag.value)") } } } } .onDelete(perform: deleteItems) } Button("Add") { addItem() } .padding(.top) } } private func addItem() { withAnimation { let newItem = Item(timestamp: Date(), tags: [Tag(value: "Hi")]) modelContext.insert(newItem) } do { try modelContext.save() } catch { print("Error saving add: \(error.localizedDescription)") } } private func deleteItems(offsets: IndexSet) { withAnimation { for index in offsets { modelContext.delete(items[index]) } } do { try modelContext.save() } catch { print("Error saving delete: \(error.localizedDescription)") } } } #Preview { ContentView() .modelContainer(for: Item.self, inMemory: true) } I hope someone can help, couldn't find anything related to this log at all.
2
0
79
Jul ’25
Extending @Model with custom macros
I am trying to extend my PersistedModels like so: @Versioned(3) @Model class MyType { var name: String init() { name = "hello" } } but it seems that SwiftData's@Model macro is unable to read the properties added by my @Versioned macro. I have tried changing the order and it ignores them regardless. version is not added to schemaMetadata and version needs to be persisted. I was planning on using this approach to add multiple capabilities to my model types. Is this possible to do with macros? VersionedMacro /// A macro that automatically implements VersionedModel protocol public struct VersionedMacro: MemberMacro, ExtensionMacro { // Member macro to add the stored property directly to the type public static func expansion( of node: AttributeSyntax, providingMembersOf declaration: some DeclGroupSyntax, in context: some MacroExpansionContext ) throws -> [DeclSyntax] { guard let argumentList = node.arguments?.as(LabeledExprListSyntax.self), let firstArgument = argumentList.first?.expression else { throw MacroExpansionErrorMessage("@Versioned requires a version number, e.g. @Versioned(3)") } let versionValue = firstArgument.description.trimmingCharacters(in: .whitespaces) // Add the stored property with the version value return [ "public private(set) var version: Int = \(raw: versionValue)" ] } // Extension macro to add static property public static func expansion( of node: SwiftSyntax.AttributeSyntax, attachedTo declaration: some SwiftSyntax.DeclGroupSyntax, providingExtensionsOf type: some SwiftSyntax.TypeSyntaxProtocol, conformingTo protocols: [SwiftSyntax.TypeSyntax], in context: some SwiftSyntaxMacros.MacroExpansionContext ) throws -> [SwiftSyntax.ExtensionDeclSyntax] { guard let argumentList = node.arguments?.as(LabeledExprListSyntax.self), let firstArgument = argumentList.first?.expression else { throw MacroExpansionErrorMessage("@Versioned requires a version number, e.g. @Versioned(3)") } let versionValue = firstArgument.description.trimmingCharacters(in: .whitespaces) // We need to explicitly add the conformance in the extension let ext = try ExtensionDeclSyntax("extension \(type): VersionedModel {}") .with(\.memberBlock.members, MemberBlockItemListSyntax { MemberBlockItemSyntax(decl: DeclSyntax( "public static var version: Int { \(raw: versionValue) }" )) }) return [ext] } } VersionedModel public protocol VersionedModel: PersistentModel { /// The version of this particular instance var version: Int { get } /// The type's current version static var version: Int { get } } Macro Expansion:
1
0
361
3w