Migrate to SwiftData

RSS for tag

Discuss the WWDC23 Session Migrate to SwiftData

View Session

Posts under wwdc2023-10189 tag

20 Posts
Sort by:
Post not yet marked as solved
2 Replies
865 Views
I converted PhotosPickerItems into Data via loadTransferrable, and stored those into an array of data in @Model class, But whenever I try to retrieve it, processing time is very high. Has anybody come up wit an easy way to do this?
Posted
by meet__071.
Last updated
.
Post not yet marked as solved
2 Replies
779 Views
I have a WidgetExtension using SwiftData (same ModelContainer setup used in the WatchApp: @main struct Watch_Widget: Widget { let kind: String = "Watch_Widget" var body: some WidgetConfiguration { StaticConfiguration(kind: kind, provider: Provider()) { entry in Watch_WidgetEntryView(entry: entry) .modelContainer(for: [Model1.self, Model2.self]) } .configurationDisplayName("App") .description("descriptions") } } Here's the same model used in the widget view: struct Watch_WidgetEntryView : View { @Query var models: [Model1] var body: some View { let gaugeVal = models.count Gauge(value: gaugeVal, in: 0...60) { Text("min") } currentValueLabel: { Text(String(Int(gaugeVal))) } .gaugeStyle(.accessoryCircular) .widgetLabel { Text("\(models.count) models") } .containerBackground(.fill.tertiary, for: .widget) } } When I build the WidgetExtension, the following error was thrown and the CK data isn't loaded properly: CloudKit setup failed because there is another instance of this persistent store actively syncing with CloudKit in this process.
Posted
by cvhu.
Last updated
.
Post not yet marked as solved
2 Replies
1.1k Views
I have deleted the app and try to run the Xcode project again. How can I remove this error ? Thread 1: Fatal error: 'try!' expression unexpectedly raised an error: Error Domain=NSCocoaErrorDomain Code=134020 "The model configuration used to open the store is incompatible with the one that was used to create the store." UserInfo={NSAffectedObjectsErrorKey=<NSManagedObject: 0x6000021c5310>
Posted
by AShaji.
Last updated
.
Post not yet marked as solved
22 Replies
2.9k Views
When running a macOS app on Xcode 15 Beta 5 (15A5209g), I get a Symbol Not Found error. Problem: App will not run. Error received. Symbol Not Found: SwiftData Default Backing For AC Environment: Version 15.0 beta 5 (15A5209g), macOS 14.0 Beta (23A5257q) App: macOS SwiftData Model @Model class Audit { init() { } } Error: dyld[875]: Symbol not found: _$s9SwiftData014DefaultBackingB0C3forACyxGxm_tcfC Referenced from: <75DF3350-4DD5-3AF4-80DA-B17B0EDD26C2> /Users/dking/Library/Developer/Xcode/DerivedData/{redacted}-bigzojxvffztaaaepdczriowvoie/Build/Products/Debug/{redacted}.app/Contents/MacOS/{redacted} Expected in: /System/Library/Frameworks/SwiftData.framework/Versions/A/SwiftData
Posted
by dkk277.
Last updated
.
Post not yet marked as solved
4 Replies
1.3k Views
I have an App Group shared between my app and its widgets. I have SwiftData's @Model, updated from the widget intent's perform() method and displayed on the app and the widget. @MainActor func perform() async throws -> some IntentResult { let context = try ModelContainer(for: MyModel.self).mainContext let myModel = try ModelContainer(for: MyModel.self).mainContext.fetch( FetchDescriptor<MyModel>(predicate: #Predicate { // The predicate is not the problem. }) ).first myModel?.functionThatModifiesMyModel() return .result() } Both the app and the widget SwiftUI views access to the model using Macros. @Environment(\.modelContext) var context @Query(sort: \.whatever) var myModel: [MyModel] But the data is never correct in the app code (the widget's data is updated correctly using the intent). Why doesn't the model make it to the app?
Posted
by serg-ios.
Last updated
.
Post marked as solved
2 Replies
1.4k Views
Hi everyone, I'm new to programming and I've been experimenting with Apple's SwiftData. I've run into an issue I can't seem to resolve. I'm creating a personal relationship manager app where I have a Relation model and an Interaction model. Relation has a one-to-many relationship with Interaction. I'm using SwiftData's @Model and @Relationship property wrappers to define these models and their relationship. I've taken inspiration from Apple's sample code, that can be found here: Adopting SwiftData for a Core Data app (WWDC23 Session: "Migrate to SwiftData") The relevant parts of the models look something like this: @Model final class Relation { ... @Relationship(.cascade, inverse: \Interaction.relation) var interactions: [Interaction] = [] ... } @Model final class Interaction { ... var relation: Relation? ... } In my SwiftUI view, I'm adding a new Interaction to a Relation like this: private func AddItem() { withAnimation { let newInteraction = Interaction(...) modelContext.insert(newInteraction) newInteraction.relation = relation relation.interactions.append(newInteraction) } } When I add a new Interaction like this, everything seems to work fine during that app session. I can see the new Interaction in my app's UI. But when I quit the app and relaunch it, the new Interaction is gone. It's as if it was never saved. I've double-checked my code and as far as I can tell, I'm using SwiftData correctly. My usage aligns with the sample code provided by Apple, and I'm not getting any errors or warnings. I think that this issue is not related to SwiftData being in Beta, because Apple's sample code works perfectly fine. I have a few questions: Is there something I'm missing about how to properly save models using SwiftData? Is there a specific step or method I need to call to persist the changes to the Relation and Interaction objects? Is there a way to debug what's going wrong when SwiftData attempts to save these changes? Any help would be greatly appreciated. Thank you in advance! Louis
Posted Last updated
.
Post not yet marked as solved
1 Replies
811 Views
The Sendable documentation says we can mark reference types as Sendable if they "internally manage access to their state." Adding Sendable conformance to my SwiftData classes silences warnings such as the following: "Non-sendable type '[Item]' returned by implicitly asynchronous call to nonisolated function cannot cross actor boundary" @Model final class Item: Sendable { var sampleProperty = "" } My understanding is that the compiler would complain if adding explicit Sendable conformance to a swift data model was breaking concurrency rules, but I wanted to check with the community to see what everyone thinks. Best, Taylor
Posted
by taychap.
Last updated
.
Post not yet marked as solved
1 Replies
646 Views
There is a new Relationship macro in Xcode Beta 6. The macro includes two new arguments: minimumModelCount and maximumModelCount. I wonder if anyone knows what these values are for and if there is another change under the hood. Relationship( _ options: PropertyOptions..., deleteRule: Schema.Relationship.DeleteRule = .nullify, minimumModelCount: Int? = 0, maximumModelCount: Int? = 0, originalName: String? = nil, inverse: AnyKeyPath? = nil, hashModifier: String? = nil )
Posted
by macrojd.
Last updated
.
Post not yet marked as solved
1 Replies
770 Views
Hi, I am looking to migrate a CoreData app which uses CloudKit to SwiftData and have two (for now) migration questions. (1) Many of the attributes have the Optional checkbox checked in the xcdatamodeld file. The corresponding SwiftData properties are marked as Optional (?) but are never not initialized to an actual value. Can I remove the ? from those property types or am I required to do this as a migration? (1a) If I'm required to do this as a migration, is this a custom migration or can I do it as a light migration. (2) I have several Int16 in the Core Data model which I'd like to make Ints in the SwiftData model. Is this a migration? Is it a custom one or can the migration make the conversion. Thank you, Daniel
Posted Last updated
.
Post not yet marked as solved
1 Replies
1.5k Views
Just for grins, I tried running the SwiftData generation tool on the existing Core Data model of a non-trivial app I've worked on for a decade or so. It's pretty substantial, and uses some more advanced features, so it seemed like an interesting test case. One of the warnings that was not reported by the UI, but which showed up in the generated code was quite a few instances of this: Entity inheritance on entity Bar (parent class Foo) is unsupported in SwiftData. Now that I'm looking at the code examples more carefully, I see an awful lot of final class, which maybe should have raised a red flag sooner. But to the best of my recollection, none of the sessions outright said that inheritance (was or) was not supported. Core Data has supported this functionality for a long time (maybe since the beginning). Assuming that this isn't supported in this first seed, are there plans to provide this functionality in the future? By the launch of iOS 17? (For the record, this model has 93 entities, of which 34 have parent entities. 14 are abstract, which I gather is also not supported. 3 of the entities are both abstract and have parent entities.)
Posted
by 610.
Last updated
.
Post marked as solved
2 Replies
1.6k Views
When trying to delete the element from my list, I always got error in my model. get { _$observationRegistrar.access(self, keyPath: \.id) return self.getValue(for: \.id) <-- ERROR: Thread 1: EXC_BREAKPOINT (code=1, subcode=0x1a949aefc) } Because I am new in development, I don't know how to solve it.
Posted Last updated
.
Post not yet marked as solved
1 Replies
818 Views
Has anyone able to run SwiftData migrations successfully? I have a Budget class with name property and I want to update it to title property while preserving all the existing data. I have defined V1 and V2 to Budget class and now I am trying to run a migration plan. // get all existing budgets // This is the V1 Budget. This contains the name property let oldBudgets = try? context.fetch(FetchDescriptor<SpendTrackerSchemaV1.Budget>()) print(oldBudgets?[0].name) // contains the value correctly like Colorado // SpendTrackerSchemaV2.Budget contains the title property } }, didMigrate: nil)``` So, oldBudgets contains the budgets with the name property and they have values too. I want to migrate all those Budgets to the Budget with title property. Any ideas or anyone else able to perform migration actions with SwiftData framework.
Posted
by azamsharp.
Last updated
.
Post not yet marked as solved
2 Replies
1.7k Views
Hi, I have an app that uses Core Data + CloudKit, and which allows sharing of entities with other iCloud users. It works in a manner similar to the sample application provided on the Apple developer site. Is this use case supported with SwiftData? The ability to share data with other iCloud users is fundamental to my app, so I cannot migrate to SwiftData unless this functionality is provided.
Posted
by circus83.
Last updated
.
Post not yet marked as solved
1 Replies
1.5k Views
I have an app that uses CoreData and I want to migrate to SwiftData. After following the Migrate to SwiftData session, I only need to point to my old Core Data file to read the old data and convert it to the new SwiftData format. My question is how do I do this? Maybe worth mentioning is that my NSPersistentContainer(name: "Model") is different to my app name. Possible Solution? According to a Tweet by Donny Wals this is done this way: By default a SwiftData ModelContainer will create its underlying storage in a file called default.store. If you want to change this so you can use an existing Core Data SQLite file, you can point your container to that file instead: // point to your old sqlite file let url = URL.applicationSupportDirectory.appending(path: "Model.sqlite") let config = ModelConfiguration(url: url) modelContainer = try ModelContainer(for: [ Movie.self ], config) My Tested Code @main struct SwiftData_TestApp: App { let url = URL.applicationSupportDirectory.appending(path: "Model.sqlite") let config = ModelConfiguration(url: url) let modelContainer = try ModelContainer(for: [ Item.self ], config) var body: some Scene { WindowGroup { ContentView() } .modelContainer(modelContainer) } } The problem here is that I don’t get it to work in the main app struct. When using this the way described in Dive deeper into SwiftData (at 6:58) I only get the error: Cannot use instance member 'url' within property initializer; property initializers run before 'self' is available PS: There seems to be an issue with this WWDC session method anyway – see this post.
Posted Last updated
.
Post not yet marked as solved
3 Replies
1.2k Views
I am trying to use SwiftData to perform a Query based on the name of the actor, which is inside a movie model. Here is the Movie model. @Model final class Movie { var title: String var year: Int @Relationship(.noAction, inverse: \Actor.movies) var actors: [Actor] = [] init(title: String, year: Int) { self.title = title self.year = year } } Here is my actual Query: _movies = Query(filter: #Predicate { $0.actors.contains(where: { $0.name.contains(actorName) }) }) But it returns nothing, even though I am passing actorName which exists in the movie.
Posted
by azamsharp.
Last updated
.
Post not yet marked as solved
0 Replies
552 Views
With Core Data you can control the journal mode as follows: let dictionaryOptions = [NSSQLitePragmasOption : ["journal_mode" : "DELETE"]] Is there a SwiftData equivalent?
Posted
by SGB.
Last updated
.