Questions tagged [swift-data]
SwiftData is a Swift-based Apple framework for managed persistence. It combines CoreData persistence technology with Swift’s modern concurrency features.
440
questions
20
votes
0
answers
3k
views
SwiftData - How to observe changes to the database outside of SwiftUI?
I have a simple example. I fetch all Trip objects from my database:
import SwiftData
@Model
class Trip {
var name: String
}
func fetch() {
let container = ModelContainer(for: Trip.self)
...
19
votes
3
answers
5k
views
How to persist custom enum with SwiftData?
I want to save a custom enum to my SwiftData model. I can get it to work that it shows and even updates the value in the UI. Though, the change of the enum var/entity isn’t persisted when relaunching ...
15
votes
3
answers
5k
views
SwiftData list bindings with @Query
Since Swift 5.5 we could create SwiftUI lists with bindings like this (e.g. see this answer):
class Item {
// ...
var isOn: Bool
}
struct ContentView: View {
@State private var items: [...
14
votes
2
answers
2k
views
How can we use custom structs/enums with the Model and Predicate macros?
Swift 5.9 and the new SwiftData framework introduce the @Model and #Predicate macros. We can now use custom enums and structs in our our models, like so:
@Model
final class Item {
var name: Name
...
13
votes
2
answers
4k
views
SwiftData @Query with #Predicate on Relationship Model
XCode 15 beta 6.
Just want to do a very simple Query Predicate where the relationship model matches:
@Query(
filter: #Predicate<Piece> {
$0.artist == selectedArtist
},
sort: [...
13
votes
4
answers
2k
views
SwiftData IOS 17 Array in random order?
Why is the order of my array random when i use the @Model macro.
class TestModel {
var name: String?
var array: \[TestModel2\]
init(name: String = "") {
self.name = name
...
13
votes
2
answers
1k
views
Crash when accessing relationship property of SwiftData model
I have two one-to-many models and I'm getting an unexplained crash when trying to access the relationship properties of the models.
The reason for the error is as follows:
Thread 1: EXC_BREAKPOINT (...
12
votes
8
answers
6k
views
How to resolve SwiftData error "Type '*' does not conform to protocol 'PersistentModel'"
Working through the betas of SwiftData and trying to stand up a PersistentContainer. I set up a modelContainer View modifier on my ContentView and conformed my class to @Model as described in various ...
11
votes
4
answers
6k
views
SwiftData query with dynamic properties in a View
I'm trying to figure out how to make a SwiftUI view that displays data from SwiftData using a query that includes variables passed into the view. I'm guessing that I won't be able to use the @Query ...
11
votes
1
answer
3k
views
Using SwiftData outside of SwiftUI
I want to create a class for handling some data at regular intervals. I've not used CoreData. Outside of a SwiftUI view, how do I get the model container and context so I can retrieve and add objects? ...
11
votes
0
answers
642
views
Sharing SwiftData with iCloud users
has anyone figured out how to use swiftdata in SwiftUI with CloudKit to share data among other users and set permissions? Thank you!
I checked apple’s documentation along with the internet in general. ...
8
votes
2
answers
2k
views
SwiftData passing @Model objects as parameters in SwiftUI
I am trying to work with multiple views in a SwiftData based SwiftUI project. However, when I create a parameter for a SwiftData @Model object in another view, when I create a sample of that object in ...
8
votes
1
answer
884
views
How to fetch with new #Predicate macro by Enum property
I'm trying to fetch some results with the new #Predicate macro. The problem appears when I try to use an enum property inside the predicate. Does anyone know if it can be done or if this is a bug?
...
7
votes
3
answers
2k
views
Combining Predicate in SwiftData
I'm trying to combine multiple Predicates of the Type with and / or.
Previously with CoreData and NSPredicate I'd just do this:
let predicate = NSPredicate(value: true)
let predicate2 = NSPredicate(...
7
votes
2
answers
607
views
SwiftData: Use ObjectID URIRepresentation to load CoreData object?
I am replacing some CoreData code within my iOS App to use the new SwiftData framework. In my original code, I was saving a CoreData object URI in UserDefaults for a quick bookmark. This allowed me to ...
6
votes
3
answers
5k
views
How to preload data into SwiftData model?
import Foundation
import SwiftData
@Model class Example: {
let name: String
let type: String
init(name: String, type: String) {
self.name = name
self.type = type
}
}
...
6
votes
2
answers
2k
views
SwiftData Modeling and saving non Nullable Relations
I have the following code:
import SwiftUI
import SwiftData
struct ContentView: View {
@Environment(\.modelContext) private var modelContext
var schoolClass: SchoolClass
var body: some ...
6
votes
1
answer
1k
views
SwiftData #Predicate do not work with Date
let startDate: Date = Date()
let predicate = #Predicate<Trip> { session in
session.startTime >= startDate
}
Does anybody has this issue when #Predicate do not work on Date? I ...
6
votes
1
answer
356
views
Unique properties of SwiftData Models when using CloudKit
Unfortunately the .unique attribute is not available for SwiftData model properties when using CloudKit.
Is there a best practice to setup a constraint like this for my own models?
For the local DB it'...
6
votes
2
answers
684
views
SwiftData: How to model inheritance?
My model class includes an array of objects that have some properties in common and some specific to only a subset. That sounds like a use case for a protocol and inheritance. However, I can't get ...
6
votes
2
answers
1k
views
How can I share SwiftData @Model between widget and app?
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(...
5
votes
1
answer
1k
views
How to resolve compiler error creating a SwiftData #Predicate?
I have been trying so many ways to resolve this issue. I am trying to fetch SwiftData records with a predicate. but everything I try results in a pair of errors:
initializer 'init(_:)' requires that '...
5
votes
1
answer
578
views
Receiving CoreData error messages when using SwiftData in Xcode 15 beta 5
I am using SwiftData in my project. All worked fine under Xcode 15 beta 4 in the simulator.
Since I changed to Xcode 15 beta 5 I am getting the following error multiple times:
CoreData: fault: One or ...
5
votes
0
answers
291
views
Crash when sorting SwiftData Query with a SortDescriptor made from a KeyPath with an optional relationship in the chain
I have the following models:
@Model
class Game {
var name: String
var firstReleasedOn: Date?
@Relationship(deleteRule: .cascade, inverse: \QueueEntry.game)
var queueEntry: QueueEntry?
...
5
votes
0
answers
566
views
SwiftData sort or filter enum property
Now that SwiftData can correctly store enums in our models, I am now having difficulties trying to filter or sort on that property.
For example
status is an enum
enum Status: String, Codable, ...
5
votes
1
answer
1k
views
SwiftData how to form a search predicate with a one to many model
I am working in Xcode 15 (beta) migrating to SwiftData and am having a hard time figuring out how to form a predicate in my one to many model. The desired result is to return a query that returns ...
4
votes
1
answer
1k
views
SwiftData compiler error on enum property with default value
Note: - This question was originally posted while Xcode 15 was in beta. With the final release of Xcode 15, the compiler gives a much clearer error stating:
A default value requires a fully qualified ...
4
votes
3
answers
4k
views
Can't Get Reference to SwiftData ModelContainer and ModelContext in MVVM Class
I'm trying to understand the new SwiftData framework. It's pretty easy to get it to work as long as
I do everything in a SwiftUI view. I'm trying to be a good coder and separate the data
from the UI ...
4
votes
1
answer
2k
views
Query() in view with model container attached shows error saying it does not have a model container
I have a function on a view that has a modelContext on its environment and that can successfully add data to the model container. But when in that same function I try to run a Query() function call I ...
4
votes
1
answer
878
views
How do I delete child items from list with SwiftData?
I'm new to SwiftUI and for my first app I decided to try SwiftData since I don't want to have to convert it to SwiftData later. My app has timers (MyTimer) and each timer has a name and several resets ...
4
votes
1
answer
1k
views
SwiftData/PersistentModel.swift:540: Fatal error: Unsupported relationship key path ReferenceWritableKeyPath
I have one to many relationship SwiftData models. However, when I tried to append data, that causes an error SwiftData/PersistentModel.swift:540: Fatal error: Unsupported relationship key path ...
4
votes
2
answers
1k
views
SwiftData struggles. Cannot insert 'MyClass' in this managed object context because it is not found in the associated managed object model
My App is crashing trying to insert into a ModelContext. Anything obvious that sticks out as to why?
@Model
class MyDataClass {
var number : String
var pageNumberInDocument : Int
...
4
votes
1
answer
691
views
SwiftData crashes when setting optional String of Codable property
I've run into an issue where setting a property on a SwiftData object to a Codable struct with an optional String crashes the app.
For example, if I have the following model object and struct :
@Model
...
4
votes
1
answer
2k
views
Error trying to use SwiftData property based on an enum with an associated value
Note: This issue was resolved with Xcode 15 RC. Unless you are inexplicably stuck using a beta version of Xcode 15, this is not the question you are looking for.
I'm trying to setup a SwiftData model ...
4
votes
1
answer
188
views
How to change entity name in SwiftData
I'm working with SwiftData in coredata project.
I have coredata models (Event, EventDate, Lecture), and convert to swiftdata model using Model macro.
enum V3Schema: VersionedSchema {
static var ...
4
votes
1
answer
613
views
Xcode 15, iOS 17 - Archive Failed - File name too long
Working on Xcode 15 GA. I'd like to archive my new iOS 17 project, which works properly on iOS and macOS (includes SwiftData library, new WidgetKit extension and StoreKit). However, when I'm trying to ...
4
votes
0
answers
447
views
SwiftData inverse Relationship stop working in Xcode 15 beta 7
This approach works before Xcode 15 beta 7:
@Model
final class Item {
var name: String
@Relationship(inverse:\Note.item) var notes: [Note]
init(name: String = "Item name") {
...
4
votes
0
answers
401
views
SwiftData - 'self' used in property access 'persistentBackingData' before 'super.init' call
I was trying to set a class to be a persistent data source using @Model annotation, and somehow this happened:
The code above is generated by the compiler and the error is located in it.
Here is my ...
4
votes
3
answers
970
views
SwiftData crash "Illegal attempt to establish a relationship"
I am using SwiftData and SwiftUI, xcode 15 beta 5. I am trying to establish relationships between entities in DB. The is a User, a Book, and an Ownership between them.
struct asdApp: App {
let ...
3
votes
2
answers
952
views
Does the #Predicate macro in Foundation/SwiftData support case-insensitive search?
I'm testing the new SwifData framework and working with the new #Predicate macro and realized that it doesn't support case-insensitive search. The macro does not work with the lowercased() method or ...
3
votes
2
answers
9k
views
Update data in SwiftData
I am trying to update data in SwiftData. The documentation, however, is literally just:
func update(expressions: [String : NSExpression],
model: any PersistentModel.Type,
where predicate: ...
3
votes
2
answers
949
views
SwiftData crashes app on get value: Thread 1: EXC_BREAKPOINT (code=1, subcode=0x101e8303c)
I'm utilizing SwiftData in my app, and I have a Tracker model with two variables: name of type String and trackerType of type TrackerType, which is another model. Retrieving name data from the Tracker ...
3
votes
1
answer
403
views
SwiftData: Type 'Schema.Relationship.Option' has no member 'cascade'
We have a Swiftdata model such as:
@Model
class MyThing {
var name:String
var myObject: MyCustomObject
//...
}
In order for "myObject" (which is also an @Model) to ...
3
votes
1
answer
1k
views
Use SwiftData @Model and ObservableObject/@Published in the same class?
import SwiftData
@Model
final class PracticeData: ObservableObject, Codable {
var score: Int
var results: [PracticeResult]
@Published var latestResult: Bool? //Error Property wrapper ...
3
votes
3
answers
2k
views
Child view not refreshing for changes on SwiftData model
I have two models like these:
@Model
class Post {
...
@Relationship(inverse: \Comment.post) var comments: [Comment]?
}
@Model
class Comment {
...
var post: Post
}
And in one of my ...
3
votes
1
answer
561
views
Is there any SwiftData equivalent willSave?
With NSManagedObject there are a few hooks like awakeFromInsert() and willSave() among others. Are there methods to override that can serve the same function? awakeFromInsert can be replaced with ...
3
votes
1
answer
1k
views
How do I specify a custom sort order for @Query in SwiftData?
I am trying to use SwiftData for an application I was using CoreData for. When I specify a sort order based on a String type, it gives me a list sorted with case-sensitivity:
If my model looks like:
...
3
votes
1
answer
2k
views
Is there a way to prevent inserting a duplicate object in SwiftData?
Coming in without a CoreData background, I was experimenting with SwiftData in an app and keep getting hit with the error:
Duplicate registration attempt for object with id PersistentIdentifier(...)
...
3
votes
1
answer
74
views
SwiftData relationship updated only after app restart
I have 2 simple models with relation 1 to many. CarMake can have multiple CarModels but one CarModel can only belong to one CarMake. Pretty straightforward.
@Model
final class CarModel {
var name: ...
3
votes
1
answer
1k
views
How to fetch swift data objects without causing memory issues?
I have been building an audio player application and have a tab in my app that queries the Song model (songs added by the user). The issue is that whenever the UI changes, swiftdata fetches the entire ...