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

Document-based SwiftData apps fail to identify a store on iPad?
When trying to run my document-based iPad app using iPadOS 18 beta and Xcode 16 beta, I get an error like the following after opening a document: Thread 1: Fatal error: Failed to identify a store that can hold instances of SwiftData._KKMDBackingData<MyProject.MyModel> from [:] In order to help track down what is going wrong, I downloaded the sample app from WWDC23 session "Build an app with SwiftData" found here: https://developer.apple.com/documentation/swiftui/building-a-document-based-app-using-swiftdata When I try to run the end-state of that sample code, I get a similar error when running the app on my iPad and creating a new deck: Thread 1: Fatal error: Failed to identify a store that can hold instances of SwiftData._KKMDBackingData<SwiftDataFlashCardSample.Card> from [:] Given that the sample project is generating the same error as my own project, is this a problem with SwiftData and document-based apps in general? Or is there a change of approach that I should try?
2
3
178
Jun ’24
How do I handle changes from sync with Swift Data?
In Core Data, you can use a pinned query generation to make sure that your app is working from a consistent view of the data store. If you have CloudKit sync turned on, and new changes come in that invalidate relationships, your app won't see them right away as long as it's looking at a pinned query generation. Since Swift Data doesn't yet support query generations, how do I deal with this issue in Swift Data apps? For example, let's say I have an address book app. I open a particular contact, and then tap a control on the screen that opens a list of images for that contact. While looking at the images, CloudKit sync retrieves changes made by other devices, which have completely removed the parent contact. How does my app know this has happened? Suppose the image browser screen needs to refer to the parent contact, or make changes to it, but the contact is no longer there because a background sync removed it.
1
0
285
Jun ’24
CloudKit + SwiftData
I am currently working on an app that utilizes SwiftData, and I am planning to integrate CloudKit. My current challenge involves managing a Day object that gets inserted when the date changes to track daily progress. Additionally, I want to prompt users to create a username during the app's onboarding process. I am concerned that this could lead to synchronization issues, such as duplicate entries for the same day or multiple user accounts being created. I assume blocking the app until everything is synced from CloudKit is not a practical solution. Does anyone have any recommendations on how to handle this? Furthermore, I would like to implement a community feature where users can post content. I noticed that CloudKit offers a public database. Is this database suitable for such a feature, or would I need to develop a separate backend to support it?
1
0
355
Jun ’24
SwiftData UndoManager leaks?
In any SwiftData project with undo enabled, I noticed that repeatedly undoing and redoing a change will cause memory to continuously climb. The larger the change, the more memory is consumed. This is surprising to me. I confirmed this on iOS and macOS using Xcode 15.4 and 16 beta. To reproduce, simply add undo/redo functionality to any project and repeatedly undo/redo a change. Memory consumption will climb continuously and will not get released. In Paul Hudson's SwiftData tutorials, he has an entire section about the numerous tricks required to get SwiftData relationships to work correctly. Does anyone know if SwiftData also requires tricks to get the UndoManager to work correctly?
1
0
128
Jun ’24
Core Data error: SQLITE_IOERR_SHMOPEN; what is this?
Hi, when setting up our Core Data stack in our iOS app (manually, with a NSManagedObjectModel/Context & NSPersistentStoreCoordinator) we have reports a rare bug we haven't been able to reproduce. Occasionally when adding a persistent store we get a NSCocoaErrorDomain 256 error (NSFileReadUnknownError) with NSSQLiteErrorDomain=4618 in the user info. That's SQLITE_IOERR_SHMOPEN , which the SQLite docs describe this way: I/O error within the xShmMap method on the sqlite3_io_methods object while trying to open a new shared memory segment It seems to specifically /not/ be a SQLITE_FULL error. Do you know what type of issue can cause this? Or where/how I can start tracking this down?
1
0
284
Jun ’24
SwiftData inside Actor leads to memory leaks
i am developing a SwiftUI App, where i need to work with relatively large amounts of data sets. While processing these data i had some issues with my app crashing randomly. As i was debugging this situation for a while i found out that dataraces were the cause for these crashes. That is why i decided to use an actor for these things.. As the actor takes care of concurrent threads, i was not having any crashes anymore, BUT, now i have to deal with some memory leaks! i've created a simple demo project to reproduce these leaks. my view: struct ContentView: View { @Environment(\.modelContext) private var modelContext // @Query private var items: [Item] var body: some View { VStack { Button(action: { Task { await testImport() } }, label: { Text("Import") }) } } } the function: func testImport() async { let actorX = testActor(container: self.modelContext.container) await actorX.cleanUp() // create dummy data: var dummyArray: [Int] = [] for i in 0...1300 { dummyArray.append(i) } await actorX.saveAssets(with: dummyArray) dummyArray = [] print("Checkpoint") } the actor: actor testActor { public var modelContainer: ModelContainer public var modelExecutor: any ModelExecutor private var context: ModelContext { modelExecutor.modelContext } public init(container: ModelContainer) { self.modelContainer = container let context = ModelContext(modelContainer) modelExecutor = DefaultSerialModelExecutor(modelContext: context) } func cleanUp() { print("starting cleanup...") do { try context.delete(model: Item.self) print("cleanup: table LocalAsset truncated") } catch { print("Failed to clear all LocalAsset data.") } } func saveAssets(with array: [Int]) { for i in 0..<array.count { let foo = array[i] let newItem = Item(timestamp: Date(), dummyInt: foo) context.insert(newItem) } try? context.save() } } And Here's a screenshot of Xcode's Instruments Leak tool: i hope somebody has any idea how to get rid of those leaks..
4
2
571
Jun ’24
SwiftData Custom Datastore Docs and Implementation
I have watched the following WWDC 2024 sessions: What’s new in SwiftData Create a custom data store with SwiftData Platform State of the Union Now, I have an application that exposes a GraphQL API endpoint that's using PostgreSQL Server 16.3 database. Next, this API returns JSON to the client application (i.e. SwiftUI app). Furthermore, I have checked the current documentation and the above videos appear to be the best reference at this time. My proposed architecture looks like the following: SwiftUI <--> SwiftData <--> PostgreStoreConfiguration && PostgreStore TBD <--> GraphQL API <--> PostgreSQL Thus, I have the following questions: Are there plans to add common out-of-the-box data store implementations for PostgreSQL, Cassandra, Redis, and so on? Will it be possible to implement data stores built to use gRPC, GraphQL, REST, and others to name a few? Will there be more documentation on the actual creation of a custom data store because the current documentation provides a slim API reference? I look forward to your feedback regarding the SwiftData custom data stores.
1
1
340
Jun ’24
SwiftData SchemaMigrationPlan and VersionedSchema not Sendable?
I've just tried to update a project that uses SwiftData to Swift 6 using Xcode 16 beta 1, and it's not working due to missing Sendable conformance on a couple of types (MigrationStage and Schema.Version): struct LocationsMigrationPlan: SchemaMigrationPlan { static let schemas: [VersionedSchema.Type] = [LocationsVersionedSchema.self] static let stages: [MigrationStage] = [] } struct LocationsVersionedSchema: VersionedSchema { static let models: [any PersistentModel.Type] = [ Location.self ] static let versionIdentifier = Schema.Version(1, 0, 0) } This code results in the following errors: error: static property 'stages' is not concurrency-safe because non-'Sendable' type '[MigrationStage]' may have shared mutable state static let stages: [MigrationStage] = [] ^ error: static property 'versionIdentifier' is not concurrency-safe because non-'Sendable' type 'Schema.Version' may have shared mutable state static let versionIdentifier = Schema.Version(1, 0, 0) ^ Am I missing something, or is this a bug in the current seed? I've filed this as FB13862584.
1
2
356
Jun ’24
SwiftData won't work with Measurement types
I'm trying out SwiftData and converting my existing data models using Structs and Codable to Classes and SwiftData. I've got a model that has a Measurement<UnitMass> type. When I run the app after converting everything to use classes with the @Model macro, I get a fatal error: SwiftData/SchemaProperty.swift:325: Fatal error: Unexpected type for CompositeAttribute: NSUnitMass. Since Measurement conforms to Codable, and SwiftData should work with Codable types, why is this not working? I also tried marking the property with @Attribute(.transformable) and it didn't make a difference.
10
12
3k
Jun ’24
SwiftData with shared and private containers
I was hoping for an update of SwiftData which adopted the use of shared and public CloudKit containers, in the same way it does for the private CloudKit container. So firstly, a big request to any Apple devs reading, for this to be a thing! Secondly, what would be a sensible way of adding a shared container in CloudKit to an existing app that is already using SwiftData? Would it be possible to use the new DataStore method to manage CloudKit syncing with a public or shared container?
2
3
546
Jun ’24
SwiftData Remote Database Updates
I just saw the new SwiftData updates, including the DataStore API. I’m wondering if, in the case of a shared remote datastore, it is possible to enable updates to the model context from the datastore without the model context explicitly requesting them (e.g., through database listeners). If I’m not mistaken, when you use CloudKit with SwiftData, this happens, right?
1
0
200
Jun ’24
Access SwiftData in Widgets
How do I access the SwiftData ModelContainer of my app inside the widget extension? Following the guide to add a Widget Extension I’ve added the necessary target to my project and enabled App Groups. I’ve seen that the Backyard Birds example code offers an example how to build this, but it encapsulates the SwiftData handling in a separate app package. Therefore the example simply points to the app package. Though, in my case I don’t host my SwiftData in an external app package, but simply inside the regular app target. So, my question is how and at which point in code do I need to access the ModelContainer?
1
1
359
Jun ’24
Using Cloud Storage With SwiftData Custom Data Store
The following videos from WWDC24 say that we can use cloud storage for our SwiftData stores. Video references below: What's new in SwiftData Create a custom data store with SwiftData When watching the videos it shows examples of how we can read and write to a JSON file as a store, rather than using the built in store that comes with SwiftData. But there are mentions that we can use cloud storage like a backend i.e. a database hosted on a server. The only thing that I'm struggling to figure out and it would be great if we had code samples for this is how to achieve using cloud storage as a store since looking at the current implementations of: DataStoreConfiguration DataStore The required functions we need to implement look synchronous rather than asynchronous so how would or could we handle fetching asynchronous data from cloud storage. So how would we handle this? Also it would be great if someone could clarify how or if there is a way to send notifications for changes to your store between different devices similar to CloudKit? Are there there any plans to provide more documentation & sample code for the questions I've asked above? Feedback FB13857743
1
4
280
Jun ’24
SwiftData context disregards unique attribute
I have a simple model with a unique field. @Model class M { @Attribute(.unique) var value: String var date: Date var answer: Int init(value: String, date: Date = .now, answer: Int = 0) { self.value = value self.date = date self.answer = answer } } I am creating new objects with let x = M(value: "x") modelContext.insert(x) The value field has a unique constraint, and I am observing these differences in iOS 18 beta (Xcode 16.0 beta) from iOS 17.5 (Xcode 15.4): Multiple objects with the same value field appear in the list. If explicit modelContext.save() is called, list is not updated with latest values. Is this something I need to adjust to, or beta issues? Full source code: https://github.com/paiv/swiftdata-insert-unique-1
2
0
188
Jun ’24
Local SwiftData to CloudKit migration
Hi, I've been working on an app that - so far - has only had to deal with offline data store. The usage is fairly simple: the user picks their favourite tv shows and networks, and they get persisted with SwiftData with all the correct relationships. Now, I would like to migrate the local storage of the users to a private CloudKit db, but every time I upgrade the app, the data seems to disappear completely. This is the snippet evolved through the attempt of migrating the data: Current Production code public static func makeModelContainer() -> ModelContainer { do { let processRequiresInMemory = ProcessInfo.processInfo.arguments.contains("inMemoryDatabasePreferred") let modelConfiguration = ModelConfiguration( isStoredInMemoryOnly: processRequiresInMemory, groupContainer: .automatic, cloudKitDatabase: .none ) let modelContainer = try ModelContainer( for: Country.self, Episode.self, Movie.self, Season.self, Show.self, Network.self, NetworkSubscription.self, migrationPlan: AppModelMigrationPlan.self, configurations: modelConfiguration ) return modelContainer } catch { fatalError("Could not initialize model container") } } Testing CloudKit enabled public static func makeModelContainer() -> ModelContainer { do { let processRequiresInMemory = ProcessInfo.processInfo.arguments.contains("inMemoryDatabasePreferred") let modelConfiguration = ModelConfiguration( "synced", isStoredInMemoryOnly: processRequiresInMemory, groupContainer: .automatic, cloudKitDatabase: .automatic ) let modelContainer = try ModelContainer( for: Country.self, Episode.self, Movie.self, Season.self, Show.self, Network.self, NetworkSubscription.self, migrationPlan: AppModelMigrationPlan.self, configurations: modelConfiguration ) return modelContainer } catch { fatalError("Could not initialize model container") } } } The differences, which I don't understand fully because I could not find documentation, are: ModelContainer(...) -> ModelContainer("synced", ...) cloudKitDatabase, from none to automatic. I have the feeling that changing the name of the configuration also changes some reference to the db itself, but if I were not to change the name, the app would have crashed because unable to migrate. What's the best approach to take here?
4
1
475
Jun ’24
Migrate Core Data to SwiftData in an App Group (& CloudKit)
Hello, I’m upgrading my app from Core Data to SwiftData. Due to my old setup the Core Data store has an explicitly name like „Something.sqlite“, because it was defined via NSPersistentContainer(name: "Something") before switching to SwiftData. Now my goal is to migrate the Core Data stack to SwiftData, while moving it to an App Group (for Widget support) as well as enable iCloud sync via CloudKit. Working Migration without App Group & CloudKit I’ve managed to get my migration running without migrating it to an App Group and CloudKit support like so: @main struct MyAppName: App { let container: ModelContainer init() { // Legacy placement of the Core Data file. let dataUrl = URL.applicationSupportDirectory.appending(path: "Something.sqlite") do { // Create SwiftData container with migration and custom URL pointing to legacy Core Data file container = try ModelContainer( for: Foo.self, Bar.self, migrationPlan: MigrationPlan.self, configurations: ModelConfiguration(url: dataUrl)) } catch { fatalError("Failed to initialize model container.") } } var body: some Scene { WindowGroup { ContentView() } .modelContainer(container) } } How To Migrate to App Group & CloudKit? I’ve already tried to use the ModelConfiguration with a name, but it seems to only look for a .store file and thus doesn’t copy over the Core Data contents. let fullSchema = Schema([Foo.self, Bar.self]) let configuration = ModelConfiguration("Something", schema: fullSchema) Can someone help me how to do this migration or point me into the right direction? I can’t find anything relating this kind of migration …
1
0
442
Jun ’24