Thanks for being a part of WWDC25!

How did we do? We’d love to know your thoughts on this year’s conference. Take the survey here

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

Can't batch delete with one-to-many to self relationship
I have a simple model that contains a one-to-many relationship to itself to represent a simple tree structure. It is set to cascade deletes so deleting the parent node deletes the children. Unfortunately I get an error when I try to batch delete. A test demonstrates: @Model final class TreeNode { var parent: TreeNode? @Relationship(deleteRule: .cascade, inverse: \TreeNode.parent) var children: [TreeNode] = [] init(parent: TreeNode? = nil) { self.parent = parent } } func testBatchDelete() throws { let config = ModelConfiguration(isStoredInMemoryOnly: true) let container = try ModelContainer(for: TreeNode.self, configurations: config) let context = ModelContext(container) context.autosaveEnabled = false let root = TreeNode() context.insert(root) for _ in 0..<10 { let child = TreeNode(parent: root) context.insert(child) } try context.save() // fails if first item doesn't have a nil parent, succeeds otherwise // which row is first is random, so will succeed sometimes try context.delete(model: TreeNode.self) } The error raised is: CoreData: error: Unhandled opt lock error from executeBatchDeleteRequest Constraint trigger violation: Batch delete failed due to mandatory OTO nullify inverse on TreeNode/parent and userInfo { NSExceptionOmitCallstacks = 1; NSLocalizedFailureReason = "Constraint trigger violation: Batch delete failed due to mandatory OTO nullify inverse on TreeNode/parent"; "_NSCoreDataOptimisticLockingFailureConflictsKey" = ( ); } Interestingly, if the first record when doing an unsorted query happens to be the parent node, it works correctly, so the above unit test will actually work sometimes. Now, this can be "solved" by changing the reverse relationship to an optional like so: @Relationship(deleteRule: .cascade, inverse: \TreeNode.parent) var children: [TreeNode]? The above delete will work fine. However, this causes issues with predicates that test counts in children, like for instance deleting only nodes where children is empty for example: try context.delete(model: TreeNode.self, where: #Predicate { $0.children?.isEmpty ?? true }) It ends up crashing and dumps a stacktrace to the console with: An uncaught exception was raised Keypath containing KVC aggregate where there shouldn't be one; failed to handle children.@count (the stacktrace is quite long and deep in CoreData's NSSQLGenerator) Does anyone know how to work around this?
5
0
779
Jan ’25
Fatal error: Duplicate keys of type 'AnyHashable' were found in a Dictionary
I get the following fatal error when the user clicks Save in AddProductionView. Fatal error: Duplicate keys of type 'AnyHashable' were found in a Dictionary. This usually means either that the type violates Hashable's requirements, or that members of such a dictionary were mutated after insertion. As far as I’m aware, SwiftData automatically makes its models conform to Hashable, so this shouldn’t be a problem. I think it has something to do with the picker, but for the life of me I can’t see what. This error occurs about 75% of the time when Save is clicked. I'm using Xcode 16.2 and iPhone SE 2nd Gen. Any help would be greatly appreciated… Here is my code: import SwiftUI import SwiftData @main struct MyApp: App { var body: some Scene { WindowGroup { ContentView() .modelContainer(for: Character.self, isAutosaveEnabled: false) } } } @Model final class Character { var name: String var production: Production var myCharacter: Bool init(name: String, production: Production, myCharacter: Bool = false) { self.name = name self.production = production self.myCharacter = myCharacter } } @Model final class Production { var name: String init(name: String) { self.name = name } } struct ContentView: View { @State private var showingSheet = false var body: some View { Button("Add", systemImage: "plus") { showingSheet.toggle() } .sheet(isPresented: $showingSheet) { AddProductionView() } } } struct AddProductionView: View { @Environment(\.dismiss) private var dismiss @Environment(\.modelContext) var modelContext @State var production = Production(name: "") @Query var characters: [Character] @State private var characterName: String = "" @State private var selectedCharacter: Character? var filteredCharacters: [Character] { characters.filter { $0.production == production } } var body: some View { NavigationStack { Form { Section("Details") { TextField("Title", text: $production.name) } Section("Characters") { List(filteredCharacters) { character in Text(character.name) } HStack { TextField("Character", text: $characterName) Button("Add") { let newCharacter = Character(name: characterName, production: production) modelContext.insert(newCharacter) characterName = "" } .disabled(characterName.isEmpty) } if !filteredCharacters.isEmpty { Picker("Select your role", selection: $selectedCharacter) { Text("Select") .tag(nil as Character?) ForEach(filteredCharacters) { character in Text(character.name) .tag(character as Character?) } } .pickerStyle(.menu) } } } .toolbar { Button("Save") { //Fatal error: Duplicate keys of type 'AnyHashable' were found in a Dictionary. This usually means either that the type violates Hashable's requirements, or that members of such a dictionary were mutated after insertion. if let selectedCharacter = selectedCharacter { selectedCharacter.myCharacter = true } modelContext.insert(production) do { try modelContext.save() } catch { print("Failed to save context: \(error)") } dismiss() } .disabled(production.name.isEmpty || selectedCharacter == nil) } } } }
2
0
776
Jan ’25
Can I change iOS version in package.swift to use SwiftData?
For the swift student challenge I was hoping to use swift data, I found that since it's a playground app, in package.swift the defaults is set to iOS 16 which means you can't use swift data. I changed it to iOS 17 and everything works but I want to know if that goes against the rules in anyway, changing th bios version in package.swift? This was the code I changed in package.swift. let package = Package( name: "ProStepper", platforms: [ .iOS("17.0") ],
3
1
547
Jan ’25
swiftdata model polymorphism?
I have a SwiftData model where I need to customize behavior based on the value of a property (connectorType). Here’s a simplified version of my model: @Model public final class ConnectorModel { public var connectorType: String ... func doSomethingDifferentForEveryConnectorType() { ... } } I’d like to implement doSomethingDifferentForEveryConnectorType in a way that allows the behavior to vary depending on connectorType, and I want to follow best practices for scalability and maintainability. I’ve come up with three potential solutions, each with pros and cons, and I’d love to hear your thoughts on which one makes the most sense or if there’s a better approach: **Option 1: Use switch Statements ** func doSomethingDifferentForEveryConnectorType() { switch connectorType { case "HTTP": // HTTP-specific logic case "WebSocket": // WebSocket-specific logic default: // Fallback logic } } Pros: Simple to implement and keeps the SwiftData model observable by SwiftUI without any additional wrapping. Cons: If more behaviors or methods are added, the code could become messy and harder to maintain. **Option 2: Use a Wrapper with Inheritance around swiftdata model ** @Observable class ParentConnector { var connectorModel: ConnectorModel init(connectorModel: ConnectorModel) { self.connectorModel = connectorModel } func doSomethingDifferentForEveryConnectorType() { fatalError("Not implemented") } } @Observable class HTTPConnector: ParentConnector { override func doSomethingDifferentForEveryConnectorType() { // HTTP-specific logic } } Pros: Logic for each connector type is cleanly organized in subclasses, making it easy to extend and maintain. Cons: Requires introducing additional observable classes, which could add unnecessary complexity. **Option 3: Use a @Transient class that customizes behavior ** protocol ConnectorProtocol { func doSomethingDifferentForEveryConnectorType(connectorModel: ConnectorModel) } class HTTPConnectorImplementation: ConnectorProtocol { func doSomethingDifferentForEveryConnectorType(connectorModel: ConnectorModel) { // HTTP-specific logic } } Then add this to the model: @Model public final class ConnectorModel { public var connectorType: String @Transient public var connectorImplementation: ConnectorProtocol? // Or alternatively from swiftui I could call myModel.connectorImplementation.doSomethingDifferentForEveryConnectorType() to avoid this wrapper func doSomethingDifferentForEveryConnectorType() { connectorImplementation?.doSomethingDifferentForEveryConnectorType(connectorModel: self) } } Pros: Decouples model logic from connector-specific behavior. Avoids creating additional observable classes and allows for easy extension. Cons: Requires explicitly passing the model to the protocol implementation, and setup for determining the correct implementation needs to be handled elsewhere. My Questions Which approach aligns best with SwiftData and SwiftUI best practices, especially for scalable and maintainable apps? Are there better alternatives that I haven’t considered? If Option 3 (protocol with dependency injection) is preferred, what’s the best way to a)manage the transient property 2) set the correct implementation and 3) pass reference to swiftdata model? Thanks in advance for your advice!
0
0
428
Jan ’25
SwiftData data duplication
I've got an application built on top of SwiftData (+ CloudKit) which is published to App Store. I've got a problem where on each app update, the data saved in the database is duplicated to the end user. Obviously this isn't wanted behaviour, and I'm really looking forward to fixing it. However, given the restrictions of SwiftData, I haven't found a single fix for this. The data duplication happens automatically on the first initial sync after the update. My guess is that it's because it doesn't detect the data already in the device, so it pulls all data from iCloud and appends it to the database where data in reality exists.
1
0
849
Jan ’25
SwiftData and CloudKit Development vs. Production Database
Hi, I'm working on a macOS app that utilizes SwiftData to save some user generated content to their private databases. It is not clear to me at which point the app I made starts using the production database. I assumed that if I produce a Release build that it will be using the prod db, but that doesn't seem to be the case. I made the mistake of distributing my app to users before "going to prod" with CloudKit. So after I realized what I had done, I inspected my CloudKit dashboard and records and I found the following: For my personal developer account the data is saved in the Developer database correctly and I can inspect it. When I use the "Act as iCloud account" feature and use one of my other accounts to inspect the data, I notice that for the other user, the data is neither in the Development environment nor the Production environment. Which leads me to believe it is only stored locally on that user's machine, since the app does in fact work, it's just not syncing with other devices of the same user. So, my question is: how do I "deploy to production"? I know that there is a Deploy Schema Changes button in the CloudKit dashboard. At which point should I press that? If I press it now, before distributing a new version of my app, will that somehow "signal" the already running apps on user's machines to start using the Production database? Is there a setting in Xcode that I need to check for my Release build, so that the app does in fact start using the production db? Is there a way to detect in the code whether the app is using the Production database or not? It would be useful so I can write appropriate migration logic, since I don't want to loose existing data users already have saved locally.
3
0
1.2k
Jan ’25
SwiftData crashes after updating to MacOS 15.2
After updating to 15.2 I am seeing frequent crashes in my in-development app related to SwiftData. For instance, I have a 100% reproducible crash when I make the app lose and regain focus. There is also a crash that seem to be triggered by a modelContext.save() call in one of my ModelActors. With both of these crashes, the issue seems to be around keeping SwiftData models up to date. The first item in the stacktrace that is not machinecode is always some getter on a SwiftData collection or object. In the console, these crashes are accompanied by output along the lines of: === AttributeGraph: cycle detected through attribute 820680 === precondition failure: setting value during update: 930592 error: the replacement path doesn't exist: "/var/folders/b7/0dw7ztp13fgfxlj19by851tw0000gn/T/swift-generated-sources/@__swiftmacro_10SpaceDebug8TodoListV5todos33_5575DE008494C519BB9FA49C405133E1LL5QueryfMa_.swift" error: the replacement path doesn't exist: "/var/folders/b7/0dw7ztp13fgfxlj19by851tw0000gn/T/swift-generated-sources/@__swiftmacro_10SpaceDebug8TodoListV5todos33_5575DE008494C519BB9FA49C405133E1LL5QueryfMa_.swift" Can't show file for stack frame : <DBGLLDBStackFrame: 0x35a57c4e0> - stackNumber:27 - name:TodoList.todos.getter. The file path does not exist on the file system: /var/folders/b7/0dw7ztp13fgfxlj19by851tw0000gn/T/swift-generated-sources/@__swiftmacro_10SpaceDebug8TodoListV5todos33_5575DE008494C519BB9FA49C405133E1LL5QueryfMa_.swiftCan't show file for stack frame : <DBGLLDBStackFrame: 0x35a57c4e0> - stackNumber:27 - name:TodoList.todos.getter. The file path does not exist on the file system: /var/folders/b7/0dw7ztp13fgfxlj19by851tw0000gn/T/swift-generated-sources/@__swiftmacro_10SpaceDebug8TodoListV5todos33_5575DE008494C519BB9FA49C405133E1LL5QueryfMa_.swiftCan't show file for stack frame : <DBGLLDBStackFrame: 0x35a5a82f0> - stackNumber:62 - name:TodoList.todos.getter. The file path does not exist on the file system: /var/folders/b7/0dw7ztp13fgfxlj19by851tw0000gn/T/swift-generated-sources/@__swiftmacro_10SpaceDebug8TodoListV5todos33_5575DE008494C519BB9FA49C405133E1LL5QueryfMa_.swift Has anyone run into something similar? I'm looking for suggestions on how to debug this. Cheers, Bastiaan
2
0
528
Jan ’25
SwiftData Migration Fail: What kind of backing data is this?
I'm trying to test migration between schemas but I cannot get it to work properly. I've never been able to get a complex migration to work properly unfortunately. I've removed a property and added 2 new ones to one of my data models. This is my current plan. enum MigrationV1toV2: SchemaMigrationPlan { static var schemas: [any VersionedSchema.Type] { [SchemaV1.self, SchemaV2.self] } static let migrateV1toV2 = MigrationStage.custom( fromVersion: SchemaV1.self, toVersion: SchemaV2.self, willMigrate: { context in print("Inside will migrate") // Get old months let oldMonths = try context.fetch(FetchDescriptor<SchemaV1.Month>()) print("Number of old months:\(oldMonths.count)") for oldMonth in oldMonths { // Convert to new month let newMonth = Month(name: oldMonth.name, year: oldMonth.year, limit: oldMonth.limit) print("Number of transactions in oldMonth: \(oldMonth.transactions?.count)") print("Number of transactions in newMonth: \(newMonth.transactions?.count)") // Convert transactions for transaction in oldMonth.transactions ?? [] { // Set action and direction let action = getAction(from: transaction) let direction = getDirection(from: transaction) // Update category if necessary var category: TransactionCategory? = nil if let oldCategory = transaction.category { category = TransactionCategory( name: oldCategory.name, color: SchemaV2.Category.Colors.init(rawValue: oldCategory.color?.rawValue ?? "") ?? .blue, icon: getCategoryIcon(oldIcon: oldCategory.icon) ) // Remove old category context.delete(oldCategory) } // Create new let new = Transaction( date: transaction.date, action: action, direction: direction, amount: transaction.amount, note: transaction.note, category: category, month: newMonth ) // Remove old transaction from month oldMonth.transactions?.removeAll(where: { $0.id == transaction.id }) // Delete transaction from context context.delete(transaction) // Add new transaction to new month newMonth.transactions?.append(new) } // Remove old month context.delete(oldMonth) print("After looping through transactions and deleting old month") print("Number of transactions in oldMonth: \(oldMonth.transactions?.count)") print("Number of transactions in newMonth: \(newMonth.transactions?.count)") // Insert new month context.insert(newMonth) print("Inserted new month into context") } // Save try context.save() }, didMigrate: { context in print("In did migrate") let newMonths = try context.fetch(FetchDescriptor<SchemaV2.Month>()) print("Number of new months after migration: \(newMonths.count)") } ) static var stages: [MigrationStage] { [migrateV1toV2] } } It seems to run fine until it gets the the line: try context.save(). At this point it fails with the following line: SwiftData/PersistentModel.swift:726: Fatal error: What kind of backing data is this? SwiftData._KKMDBackingData<Monthly.SchemaV1.Transaction> Anyone know what I can do about this?
1
0
394
Jan ’25
Triggering a Live Activity from a Widget-Based App Intent
Hello everyone, I have an app leveraging SwiftData, App Intents, Interactive Widgets, and a Control Center Widget. I recently added Live Activity support, and I’m using an App Intent to trigger the activity whenever the model changes. When the App Intent is called from within the app, the Live Activity is created successfully and appears on both the Lock Screen and in the Dynamic Island. However, if the same App Intent is invoked from a widget, the model is updated as expected, but no Live Activity is started. Here’s the relevant code snippet where I call the Live Activity: ` await LiveActivityManager.shared.newSessionActivity(session: session) And here’s how my attribute is defined: struct ContentState: Codable, Hashable { var session: Session } } Is there any known limitation or workaround for triggering a Live Activity when the App Intent is initiated from a widget? Any guidance or best practices would be greatly appreciated. Thank you! David
1
0
563
Jan ’25
SwiftData and async functions
Hello, I recently published an app that uses Swift Data as its primary data storage. The app uses concurrency, background threads, async await, and BLE communication. Sadly, I see my app incurs many fringe crashes, involving EXC_BAD_ACCESS, KERN_INVALID_ADDRESS, EXC_BREAKPOINT, etc. I followed these guidelines: One ModelContainer that is stored as a global variable and used throughout. ModelContexts are created separately for each task, changes are saved manually, and models are not passed around. Threads with different ModelContexts might manipulate and/or read the same data simultaneously. I was under the impression this meets the usage requirements. I suspect perhaps the issue lies in my usage of contexts in a single await function, that might be paused and resumed on a different thread (although same execution path). Is that the case? If so, how should SwiftData be used in async scopes? Is there anything else particularly wrong in my approach?
4
0
1.1k
Mar ’25
Model instance invalidated, backing data could no longer be found in the store
I have been recently getting the following error seemingly randomly, when an event handler of a SwiftUI view accesses a relationship of a SwiftData model the view holds a reference to. I haven't yet found a reliable way of reproducing it: SwiftData/BackingData.swift:866: Fatal error: This model instance was invalidated because its backing data could no longer be found the store. PersistentIdentifier(id: SwiftData.PersistentIdentifier.ID(url: COREDATA_ID_URL), implementation: SwiftData.PersistentIdentifierImplementation) What could cause this error? Could you suggest me a workaround?
2
0
860
Dec ’24
SwiftData Query filter().first crashed in iOS18.2
Hi There, I have a iOS App which has been published and purely managing data by SwiftData. I use following simple codes everywhere in Views: ... @Query var items: [Item] .... if let firstItem = items.first( where: {...}) { ... Then I encountered crash at Query that _items.wrapperdValue has some errors. Then I tried to split first(where...) into ordinary way: let filteredItems = items.filter(...) if let firstItem = filteredItems.first { ... It runs OK. Is it a bug in SwiftData in 18.2 or I missed some steps to facilitate SwiftData macros?
1
0
354
Dec ’24
Filter a list of Item objects on a related Product Object passed as a Bindable
I'm currently developing a SwiftUI application that utilizes SwiftData for data management. I am facing a challenge when trying to filter a query. Specifically, I want to filter a list of Item objects to match a Product instance that is passed to my View. error : Instance member 'product' cannot be used on type 'MainItemListEncap'; did you mean to use a value of this type instead The view // // 311.1.1. MainRefToItem.swift // ComparePrice // // Created by Herman VAN CAUWELAERT on 11/12/2024. // import SwiftUI import SwiftData struct MainItemListEncap: View { @Bindable var product: Product @Query( filter: #Predicate { item in item.productGroup == product }, sort: [SortDescriptor(\Item.name)] ) var items: [Item] @Environment(\.modelContext) var modelContext var body: some View { ForEach(items) { item in VStack(alignment: .leading) { Text(item.name) Text(item.description) } } } } the product class. import SwiftData import Foundation @Model final class Product: CustomStringConvertible, CustomDebugStringConvertible { @Attribute(.unique) var productName: String var productDescription: String var outputCurrency: String // Gebruik een `String` als opslag voor `outputSystem` var outputSystemRawValue: String = MeasurementSystem.metric.rawValue // Computed property om `MeasurementSystem` te gebruiken var outputSystem: MeasurementSystem { get { MeasurementSystem(rawValue: outputSystemRawValue) } set { outputSystemRawValue = newValue.rawValue } } // er zijn verschillend item versies voor een product // als er een hoofdproduct gedelete wordt, dan zullen alle onderliggende items ook gedelete worden @Relationship(deleteRule: .cascade, inverse: \Item.productGroup) var refToItems = [Item]() init(productName: String = "", productDescription: String = "what is this product", outputCurrency: String = "EUR", outputSystem: MeasurementSystem = MeasurementSystem.metric) { self.productName = productName self.productDescription = productDescription self.outputCurrency = outputCurrency self.outputSystem = outputSystem } } the item class import Foundation import SwiftData @Model final class Item: CustomStringConvertible, CustomDebugStringConvertible { var timestamp: Date @Attribute(.unique) var name: String var productGroup: Product? var shop: String //TODO: becomes Shop var price: Double var currency: String var quantity: Double var unit: String //TODO: becomes Unit var isShown : Bool var minimumQuantity: String var rateStr: String { conversionRate != nil ? " (rate: \(ValueFormatter.shared.format(conversionRate!)))" : "" } init(timestamp: Date = Date() , name: String , shop: String = "Colruyt" , price:Double = 1.00 , currency: String = "EUR" , quantity: Double = 1.0 , unit: String = "g" , isShown:Bool = true , conversionRate: Decimal? = 1 , minimumQuantity: String = "1" ) { self.timestamp = timestamp self.name = name self.shop = shop self.price = price self.currency = currency self.quantity = quantity self.unit = unit self.isShown = isShown self.conversionRate = conversionRate self.minimumQuantity = minimumQuantity } }
2
0
313
Dec ’24
SwiftData and 'NSKeyedUnarchiveFromData' should not be used to for un-archiving and will be removed in a future release
I get this red warning in Xcode every time my app is syncing to the iCloud. My model has only basic types and enum that conform to Codable so i'm not sure what is the problem. App is working well, synchronization works. But the warning doesn't look good. Maybe someone has idea how to debug it.
2
0
877
Dec ’24
Use CoreData alongside SwiftData for the "Sharing" feature in the app.
Hello! 😊 I currently manage an app called MoneyKeeper that uses SwiftData for its data storage framework. Many users have requested a "sharing" feature, but unfortunately, SwiftData does not yet support this functionality, and it’s unclear when it will. 😭 Initially, I considered using CloudKit and CKSyncEngine to implement quick synchronization and sharing. However, due to the complexity of the current data model’s relationships, modeling it with CloudKit’s schema alone seemed overly complicated and likely to introduce bugs. As a result, I’ve decided to implement the sharing feature using CoreData and CloudKit. My plan to avoid conflicts with SwiftData includes: Keeping the local storage locations for SwiftData and CoreData separate. Using entirely separate CloudKit containers for SwiftData and CoreData. I believe these measures will minimize potential issues, but I’m wondering if there’s anything else I should consider. Using both SwiftData (for the personal database) and CoreData (for the shared database) feels like it could lead to significant technical debt in the future, and I anticipate encountering even more challenges during actual implementation. I’d greatly appreciate your valuable insights on this matter. 🙏 The app MoneyKeeper, currently operated using SwiftData. https://apps.apple.com/app/id6514279917
1
0
857
Dec ’24
SwiftData + CKSyncEngine
Hi, I'm building a habit tracking app for iOS and macOS. I want to use up to date technologies, so I'm using SwiftUI and SwiftData. I want to store user data locally on device and also sync data between device and iCloud server so that the user could use the app conveniently on multiple devices (iPhone, iPad, Mac). I already tried SwiftData + NSPersistentCloudKitContainer, but I need to control when to sync data, which I can't control with NSPersistentCloudKitContainer. For example, I want to upload data to server right after data is saved locally and download data from server on every app open, on pull-to-refresh etc. I also need to monitor sync progress, so I can update the UI and run code based on the progress. For example, when downloading data from server to device is in progress, show "Loading..." UI, and when downloading finishes, I want to run some app business logic code and update UI. So I'm considering switching from NSPersistentCloudKitContainer to CKSyncEngine, because it seems that with CKSyncEngine I can control when to upload and download data and also monitor the progress. My database schema (image below) has relationships - "1 to many" and "many to many" - so it's convenient to use SwiftData (and underlying CoreData). Development environment: Xcode 16.1, macOS 15.1.1 Run-time configuration: iOS 18.1.1, macOS 15.1.1 My questions: 1-Is it possible to use SwiftData for local data storage and CKSyncEngine to sync this local data storage with iCloud? 2-If yes, is there any example code to implement this? I've been studying the "CloudKit Samples: CKSyncEngine" demo app (https://github.com/apple/sample-cloudkit-sync-engine), but it uses a very primitive approach to local data storage by saving data to a JSON file on disk. It would be very helpful to have the same demo app with SwiftData implementation! 3-Also, to make sure I don't run into problems later - is it okay to fire data upload (sendChanges) and download (fetchChanges) manually with CKSyncEngine and do it often? Are there any limits how often these functions can be called to not get "blocked" by the server? 4-If it's not possible to use SwiftData for local data storage and CKSyncEngine to sync this local data storage with iCloud, then what to use for local storage instead of SwiftData to sync it with iCloud using CKSyncEngine? Maybe use SwiftData with the new DataStore protocol instead of the underlying CoreData? All information highly appreciated! Thanks, Martin
3
0
1.2k
Dec ’24
Ongoing Issues with ModelActor in SwiftData?
After the problems with the ModelActor in iOS 18, it seemed like the ModelActor became more stable with iOS 18.1 and macOS 15.1. However, I’m still encountering many problems and crashes. I wanted to ask if these issues are related to my persistence layer architecture or if they’re still inherent to the ModelActor itself. I’ve generally followed the blog posts: https://fatbobman.com/en/posts/practical-swiftdata-building-swiftui-applications-with-modern-approaches/ and https://brightdigit.com/tutorials/swiftdata-modelactor/ and aim to achieve the following: I have a single DataProvider that holds the ModelContainer and uses it to configure and initialize a single DataHandler. These are created once at app launch and injected into the SwiftUI view hierarchy as EnvironmentObjects. Since I need to access the SwiftData models not only in SwiftUI but also indirectly in ViewModels or UIKit views, all read operations on the models should go through the DataProvider ( ModelContainrs MainContext), while all other CRUD operations are handled centrally via the single DataHandler (executed within a single ModelActor). Additionally, I want to monitor the entire container using another ModelActor, initialized in the DataProvider, which tracks changes to objects using TransactionHistory. I’ve managed to implement this to some extent, but I’m facing two main issues: ModelActor and Main Actor Requirement The ModelActor only updates SwiftUI views when initialized via the main context of the ModelContainer and therefore runs on the Main Actor. It would be ideal for this to work in the background, but the issue with the ModelActor that existed previously doesn’t seem to have been resolved in iOS 18.1/macOS 15.1—am I wrong about this? Frequent Crashes (more severe) Crashes occur, especially when multiple windows on macOS or iPadOS access the same DataHandler to update models. This often leads to crashes during read operations on models by a SwiftUI view, with logs like: Object 0x111f15480 of class _ContiguousArrayStorage deallocated with non-zero retain count 3. This object's deinit, or something called from it, may have created a strong reference to self which outlived deinit, resulting in a dangling reference. error: the replacement path doesn't exist: "/var/folders/gs/8rwdjczj225d1pj046w3d97c0000gn/T/swift-generated-sources/@__swiftmacro_12SwiftDataTSI3TagC4uuID18_PersistedPropertyfMa_.swift" Can't show file for stack frame : <DBGLLDBStackFrame: 0x34d28e170> - stackNumber:1 - name:Tag.uuID.getter. The file path does not exist on the file system: /var/folders/gs/8rwdjczj225d1pj046w3d97c0000gn/T/swift-generated-sources/@__swiftmacro_12SwiftDataTSI3TagC4uuID18_PersistedPropertyfMa_.swift This error usually happens when there are multiple concurrent accesses to the DataHandler/ModelActor. However, crashes also occur sporadically during frequent accesses from a single view with an error like "the replacement path doesn't exist." It also seems like having multiple ModelActors, as in this case (one for observation and one for data changes), causes interference and instability. The app appears to crash less frequently when the observer is not initialized, but I can’t verify this—it might just be a coincidence. My Question: Am I fundamentally doing something wrong with the ModelActors or the architecture of my persistence layer?
4
0
1.3k
Dec ’24
Ongoing Issues with ModelActor in SwiftData?
After the significant issues with the ModelActor in iOS 18, it seemed like the ModelActor became more stable with iOS 18.1 and macOS 15.1. However, I’m still encountering problems and crashes. I wanted to ask if these issues are related to my persistence layer architecture or if they’re still inherent to the ModelActor itself. I’ve generally followed the blog posts: https://fatbobman.com/en/posts/practical-swiftdata-building-swiftui-applications-with-modern-approaches/ and https://brightdigit.com/tutorials/swiftdata-modelactor/ and aim to achieve the following: I have a single DataProvider that holds the ModelContainer and uses it to configure and initialize a single DataHandler. These are created once at app launch and injected into the SwiftUI view hierarchy as EnvironmentObjects. Since I need to access the SwiftData models not only in SwiftUI but also indirectly in ViewModels or UIKit views, all read operations on the models should go through the DataProvider (and its MainContext), while all other CRUD operations are handled centrally via the single DataHandler (executed within a single ModelActor). Additionally, I want to monitor the entire container using another ModelActor, initialized in the DataProvider, which tracks changes to objects using TransactionHistory. I’ve managed to implement this to some extent, but I’m facing two main issues: 1. ModelActor and Main Actor Requirement The ModelActor only updates SwiftUI views when initialized via the maincontext of the ModelContainer and therefore runs on the Main Actor. It would be ideal for this to work in the background, but the issue with the ModelActor that existed previously doesn’t seem to have been resolved in iOS 18.1/macOS 15.1—am I wrong about this? 2. Frequent Crashes (more severe) Crashes occur, especially when multiple windows on macOS or on iPad access the same DataHandler to update models. This often leads to crashes during read operations on models by a SwiftUI view (but not only), with logs like: error: the replacement path doesn't exist: "/var/folders/gs/8rwdjczj225d1pj046w3d97c0000gn/T/swift-generated-sources/@__swiftmacro_12SwiftDataTSI3TagC4uuID18_PersistedPropertyfMa_.swift" Can't show file for stack frame : <DBGLLDBStackFrame: 0x34d28e170> - stackNumber:1 - name:Tag.uuID.getter. The file path does not exist on the file system: /var/folders/gs/8rwdjczj225d1pj046w3d97c0000gn/T/swift-generated-sources/@__swiftmacro_12SwiftDataTSI3TagC4uuID18_PersistedPropertyfMa_.swift This error usually happens when there are multiple concurrent accesses to the DataHandler/ModelActor. However, crashes also occur sporadically during frequent accesses from a single view with an error like "the replacement path doesn't exist." It also seems like having multiple ModelActors, as in this case (one for observation and one for data changes), causes interference and instability. The app appears to crash less frequently when the observer is not initialized, but I can’t verify this—it might just be a coincidence. My Question: Am I fundamentally doing something wrong with the ModelActors or the architecture of my persistence layer?
1
0
487
Dec ’24
Correct way to remove arrays containing model objects in SwiftData
Are there any differences (either performance or memory considerations) between removing an array of model objects directly using .removeAll() vs using modelContext? Or, are they identical? Attached below is an example to better illustrate the question (i.e., First Way vs Second Way) // Model Definition @Model class GroupOfPeople { let groupName: String @Relationship(deleteRule: .cascade, inverse: \Person.group) var people: [Person] = [] init() { ... } } @Model class Person { let name: String var group: GroupOfPeople? init() { ... } } // First way struct DemoView: View { @Query private groups: [GroupOfPeople] var body: some View { List(groups) { group in DetailView(group: group) } } } struct DetailView: View { let group: GroupOfPeople var body: some View { Button("Delete All Participants") { group.people.removeAll() } } // Second way struct DemoView: View { @Query private groups: [GroupOfPeople] var body: some View { List(groups) { group in DetailView(group: group) } } } struct DetailView: View { @Environment(\.modelContext) private var context let group: GroupOfPeople var body: some View { Button("Delete All Participants") { context.delete(model: Person.self, where: #Predicate { $0.group.name == group.name }) } // assuming group names are unique. more of making a point using modelContext instead }
0
0
286
Dec ’24