Search results for

“SwiftData inheritance relationship”

4,986 results found

Post

Replies

Boosts

Views

Activity

Trouble with Persisting One-to-Many Relationship Data in SwiftData, What am I Missing?
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 newI
2
0
2.7k
Jul ’23
SwiftData Crash On Models With Relationships Deletion
It seems that when you delete model objects with a relationship there seems to be a crash occurring if the collection your observing is tied to a ForEach. Below is an example of the models in SwiftData @Model class Category { @Attribute(.unique) var title: String var items: [Item]? init(title: String = ) { self.title = title } } The relationship is defined between the category and the item @Model final class Item { var title: String var timestamp: Date var isCritical: Bool var isCompleted: Bool @Relationship(.nullify, inverse: Category.items) var category: Category? init(title: String = , timestamp: Date = .now, isCritical: Bool = false, isCompleted: Bool = false) { self.title = title self.timestamp = timestamp self.isCritical = isCritical self.isCompleted = isCompleted } } So if I were to create a category individually so i can later tag it to an item i'm just following the standard proceedure of creating a category and inserting it into the context as you can see below Bu
5
0
3.6k
Jun ’23
SwiftData `unsupportedPredicate` when `Query` via a relationship
private struct TransactionItemsView: View { init(journal: Journal, budgetMode: Bool) { let journalID = journal.id! _entries = .init(filter: #Predicate { $0.journal!.id! == journalID }, sort: .date, order: .reverse) // HERE: Query encountered an error: SwiftData.SwiftDataError(_error: SwiftData.SwiftDataError._Error.unsupportedPredicate) } @Query var entries: [Entry] ... } My model: // unimportant code like `init` is hidden @Model final class Journal { ... var id: UUID! @Relationship(deleteRule: .cascade, inverse: Entry.journal) var entries: [Entry]! = [] } @Model final class Entry { ... @Relationship(deleteRule: .nullify) var journal: Journal! }
1
0
1.1k
Sep ’23
SwiftData crash when using a @Query sort descriptor with a relationship
I am using SwiftData for storage and have a view that uses the @Query property wrapper with a sort descriptor that points to a relationship on a model. In a release build on device running iOS 18.3, the app crashes. This is the line that crashes: @Query(sort: Item.info.endDate, order: .reverse) private var items: [Item] Item has a relationship to ItemInfo, which is where the endDate property is defined. This code works in debug and on a simulator. In the project referenced here: https://github.com/lepolt/swiftdata-crash, change the scheme build configuration to “Release” and run on device. The app will crash. Using Xcode Version 16.2 (16C5032a) iPhone 12, iOS 18.3 (22D60)
9
0
1.5k
Jan ’25
Issues with SwiftData One-to-Many Relationships
I've been working with SwiftData and encountered a perplexing issue that I hope to get some insights on. When using a @Model that has a one-to-many relationship with another @Model, I noticed that if there are multiple class variables involved, SwiftData seems to struggle with correctly associating each variable with its corresponding data. For example, in my code, I have two models: Book and Page. The Book model has a property for a single contentPage and an optional array of pages. However, when I create a Book instance and leave the pages array as nil, iterating over pages unexpectedly returns the contentPage instead. You can check out the code for more details here. Has anyone else faced this issue or have any suggestions on how to resolve it? Any help would be greatly appreciated! I dont understand. How does using appended help here? I am not adding anything to the array. Here is the summary The following code defines two SwiftData models: Book and Page. In the Book cl
3
0
1.1k
Oct ’24
SwiftData Query relationships not working
Overview I have 2 models: Deparment and Student Each Department can contain multiple students Each Student can only be in one Department I have DepartmentList, tapping on the department should take it to the StudentList which lists all students in the department Problem When I use Query in StudentList to filter only students for a specific department id, no students are shown. Questions: What should I do to list the students in a department? (see complete code below). let filter = #Predicate { student in student.department?.id == departmentID } let query = Query(filter: filter, sort: .name) _students = query Complete code App @main struct SchoolApp: App { var body: some Scene { WindowGroup { ContentView() } .modelContainer(for: [Department.self, Student.self]) } } Department import Foundation import SwiftData @Model class Department { var id: UUID var name: String var students: [Student] init( id: UUID, name: String, students: [Student] = [] ) { self.id = id self.name = name self.students = students
10
0
4.1k
Jun ’23
SwiftData FatalError Unknown Relationship Key
Some of our users on iOS 17.5+ started to encounter crash due to: SwiftData/BackingData.swift:669: Fatal error: Unknown Relationship Key - subscription) We have tried using SwiftData on the MainActor only but an issues still effects some of our users. Our models look like these: @Model public final class ProfileModel { public static let fetchDescriptor = FetchDescriptor.self public enum Gender: Codable { case female case male case other } public enum Units: Codable { case imperial case metric } public enum Eating: Codable { case empath case enthusiast case explorer case guardian case harmonizer case pacifier case regulator case stoic case iosDefault } public enum RegistrationSource: Codable { case iOS case web } public enum NHE: Codable { case combined case emotional case mindless } public enum Goal: Codable { case beHealthier case energyIncrease case healthyHabits case looseWeight case relationshipsWithFood } public enum WeightLossFocus: Codable { case activity case healthyHabits c
0
0
470
Jun ’24
SwiftData filter many to many relationship
my question is how to filter in search text for city.name in Concert ? i tried to reach city name using nested compact map but couldn't handle it. class Concert { var kindOf : String var city : [City] } class City { var name : String @Relationship(inverse: Concert.city) var concert : [Concert] } @Query var concerts : [Concert] @State var searchQuery : String = var filteredConcert : [Concert] { if searchQuery.isEmpty { return concerts } let filteredConcerts = concerts.compactMap { concert in let kindOfContainsSearch = concert.kindOf.range(of: searchQuery) != nil return (kindOfContainsSearch ) ? concert : nil } return filteredConcerts }
0
0
511
Jan ’24
SwiftData one-to-many Relationship not working
Hello, I have the problem that my todos are not only assigned to one project (one-to-many). They are displayed in the same way in every project. What have I done wrong? Die HauptApp: import SwiftData @main struct consiliaApp: App { var body: some Scene { WindowGroup { ProjektView() }.modelContainer(for: Projekte.self) } } Das Datenmodell: import SwiftData @Model final class Projekte { var name: String var info: String var startdate: Date var enddate: Date var startadresse: String var zieladresse: String var priority: Int @Relationship(deleteRule: .cascade, inverse: Todo.projekte) var todos: [Todo]? = [] init(name: String, info: String, startdate: Date, enddate: Date, startadresse: String, zieladresse: String, priority: Int) { self.name = name self.info = info self.startdate = startdate self.enddate = enddate self.startadresse = startadresse self.zieladresse = zieladresse self.priority = priority } } @Model class Todo { var name: String // @Relationship var projekte: Projekt
0
0
742
Jan ’24
Reply to XCode 8.1 -> duplicate symbol __TMRbBp
Same problem here when archiving (or compiling release schema), error points to two class with inherit relationship, the strange thing is that it just for specific class, but no luck if only to changed the class name.I empty the class implementation, then the two .o files (for the two classed) are dispear, but two other files (include classes with inherit relationship) are listed in the error.
Oct ’16
Debugging/Fixing deleted relationship objects with SwiftData
Using SwiftData and this is the simplest example I could boil down: @Model final class Item { var timestamp: Date var tag: Tag? init(timestamp: Date) { self.timestamp = timestamp } } @Model final class Tag { var timestamp: Date init(timestamp: Date) { self.timestamp = timestamp } } Notice Tag has no reference to Item. So if I create a bunch of items and set their Tag. Later on I add the ability to delete a Tag. Since I haven't added inverse relationship Item now references a tag that no longer exists so so I get these types of errors: SwiftData/BackingData.swift:875: Fatal error: This model instance was invalidated because its backing data could no longer be found the store. PersistentIdentifier(id: SwiftData.PersistentIdentifier.ID(url: x-coredata://EEC1D410-F87E-4F1F-B82D-8F2153A0B23C/Tag/p1), implementation: SwiftData.PersistentIdentifierImplementation) I think I understand now that I just need to add the item reference to Tag and SwiftData will nullify all Item referenc
2
0
382
Mar ’25
SwiftData many-to-many relationship doesn't populate the inverse.
I am using SwiftData in my iOS app and I created 2 models: @Model class Track { // ... var artists: [Artist] // ... init(artists: [Artist] = []) { self.artists = artists } } @Model class Artist { // ... @Relationship(inverse: Track.artists) var tracks: [Track] // ... init() { self.tracks = [] } } And I populate my container like this: // // MyApp.swift // import SwiftUI import SwiftData @main struct NyxApp: App { // TODO: handle exception let container = try! ModelContainer(for: Track.self, Artist.self) var body: some Scene { WindowGroup { ContentView() } .modelContainer(container) } } // // Function to add debug data // { let artist = Artist( // ... ) let track = Track( // ... artists: [artist], // ... ) context.insert(track) try! context.save() } The Track entity stores the Artist in Track.artists temporarily, but when I restart the app, the array is empty. The Artist.tracks array won't even get populated after inserting the track. I didn't find much useful information about many-
0
0
904
Feb ’24
Reply to SwiftData @Model: Optional to-many relationship is never nil at runtime
SwiftData default store is based on Core Data. As a historical implementation detail, at runtime, a Core Data to-many relationship, once persisted, is always a [], and never a nil. To adapt this behavior in an effective way, SwiftData always initializes a nil to-many relationship with an empty collection at runtime. So to your first question, the behavior that optional to-many relationships in SwiftData are never nil at runtime is as-designed. The requirement that relationships must be optional is a way to express that NSPersistentCloudKitContainer does not handle relationships atomically, and is enforced by a schema validator at compile time. The validation doesn't have any impact at runtime, and so SwiftData to-many relationships being [] at runtime doesn't break the CloudKit synchronization. To use SwiftData + CloudKit, you make sure your model schema is compatible with the rules so the schema validator doesn
Jan ’26
Reply to Finding source for SwiftData array behaviour
I am not completely clear what your question is, but based on the description, it seems to be related to the order of SwiftData array, and so I'd start with that. In a SwiftData model that contains an array, the array element can be a Codable type or a SwiftData model, as shown below: @Model class Department { @Relationship(deleteRule: .cascade, inverse: Employee.department) var employees: [Employee] = [Employee]() // Relationship var aliasNames: [String] = [] // `String` is Codable ... } @Model class Employee { var department: Department? ... } Here employees is a SwiftData relationship, and aliasNames is an attribute of a string array. Every time you fetch Department and access the attribute and relationship, the elemet order of department.aliasNames is the same, but that of department.employees is not. The reason is that SwiftData uses Core Data as its default store, and in Core Data, a too-many relationship is expres
Topic: UI Frameworks SubTopic: SwiftUI Tags:
Oct ’25
Trouble with Persisting One-to-Many Relationship Data in SwiftData, What am I Missing?
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 newI
Replies
2
Boosts
0
Views
2.7k
Activity
Jul ’23
SwiftData Crash On Models With Relationships Deletion
It seems that when you delete model objects with a relationship there seems to be a crash occurring if the collection your observing is tied to a ForEach. Below is an example of the models in SwiftData @Model class Category { @Attribute(.unique) var title: String var items: [Item]? init(title: String = ) { self.title = title } } The relationship is defined between the category and the item @Model final class Item { var title: String var timestamp: Date var isCritical: Bool var isCompleted: Bool @Relationship(.nullify, inverse: Category.items) var category: Category? init(title: String = , timestamp: Date = .now, isCritical: Bool = false, isCompleted: Bool = false) { self.title = title self.timestamp = timestamp self.isCritical = isCritical self.isCompleted = isCompleted } } So if I were to create a category individually so i can later tag it to an item i'm just following the standard proceedure of creating a category and inserting it into the context as you can see below Bu
Replies
5
Boosts
0
Views
3.6k
Activity
Jun ’23
SwiftData `unsupportedPredicate` when `Query` via a relationship
private struct TransactionItemsView: View { init(journal: Journal, budgetMode: Bool) { let journalID = journal.id! _entries = .init(filter: #Predicate { $0.journal!.id! == journalID }, sort: .date, order: .reverse) // HERE: Query encountered an error: SwiftData.SwiftDataError(_error: SwiftData.SwiftDataError._Error.unsupportedPredicate) } @Query var entries: [Entry] ... } My model: // unimportant code like `init` is hidden @Model final class Journal { ... var id: UUID! @Relationship(deleteRule: .cascade, inverse: Entry.journal) var entries: [Entry]! = [] } @Model final class Entry { ... @Relationship(deleteRule: .nullify) var journal: Journal! }
Replies
1
Boosts
0
Views
1.1k
Activity
Sep ’23
SwiftData crash when using a @Query sort descriptor with a relationship
I am using SwiftData for storage and have a view that uses the @Query property wrapper with a sort descriptor that points to a relationship on a model. In a release build on device running iOS 18.3, the app crashes. This is the line that crashes: @Query(sort: Item.info.endDate, order: .reverse) private var items: [Item] Item has a relationship to ItemInfo, which is where the endDate property is defined. This code works in debug and on a simulator. In the project referenced here: https://github.com/lepolt/swiftdata-crash, change the scheme build configuration to “Release” and run on device. The app will crash. Using Xcode Version 16.2 (16C5032a) iPhone 12, iOS 18.3 (22D60)
Replies
9
Boosts
0
Views
1.5k
Activity
Jan ’25
Issues with SwiftData One-to-Many Relationships
I've been working with SwiftData and encountered a perplexing issue that I hope to get some insights on. When using a @Model that has a one-to-many relationship with another @Model, I noticed that if there are multiple class variables involved, SwiftData seems to struggle with correctly associating each variable with its corresponding data. For example, in my code, I have two models: Book and Page. The Book model has a property for a single contentPage and an optional array of pages. However, when I create a Book instance and leave the pages array as nil, iterating over pages unexpectedly returns the contentPage instead. You can check out the code for more details here. Has anyone else faced this issue or have any suggestions on how to resolve it? Any help would be greatly appreciated! I dont understand. How does using appended help here? I am not adding anything to the array. Here is the summary The following code defines two SwiftData models: Book and Page. In the Book cl
Replies
3
Boosts
0
Views
1.1k
Activity
Oct ’24
SwiftData Query relationships not working
Overview I have 2 models: Deparment and Student Each Department can contain multiple students Each Student can only be in one Department I have DepartmentList, tapping on the department should take it to the StudentList which lists all students in the department Problem When I use Query in StudentList to filter only students for a specific department id, no students are shown. Questions: What should I do to list the students in a department? (see complete code below). let filter = #Predicate { student in student.department?.id == departmentID } let query = Query(filter: filter, sort: .name) _students = query Complete code App @main struct SchoolApp: App { var body: some Scene { WindowGroup { ContentView() } .modelContainer(for: [Department.self, Student.self]) } } Department import Foundation import SwiftData @Model class Department { var id: UUID var name: String var students: [Student] init( id: UUID, name: String, students: [Student] = [] ) { self.id = id self.name = name self.students = students
Replies
10
Boosts
0
Views
4.1k
Activity
Jun ’23
How do you create an inverse relationship to the same model in SwiftData
I have a Person model that needs to have a relationships with other instances of Person objects. CloudKit requires an inverse relationship be setup but I don't know how to configure it.
Replies
1
Boosts
0
Views
1.4k
Activity
Aug ’23
SwiftData FatalError Unknown Relationship Key
Some of our users on iOS 17.5+ started to encounter crash due to: SwiftData/BackingData.swift:669: Fatal error: Unknown Relationship Key - subscription) We have tried using SwiftData on the MainActor only but an issues still effects some of our users. Our models look like these: @Model public final class ProfileModel { public static let fetchDescriptor = FetchDescriptor.self public enum Gender: Codable { case female case male case other } public enum Units: Codable { case imperial case metric } public enum Eating: Codable { case empath case enthusiast case explorer case guardian case harmonizer case pacifier case regulator case stoic case iosDefault } public enum RegistrationSource: Codable { case iOS case web } public enum NHE: Codable { case combined case emotional case mindless } public enum Goal: Codable { case beHealthier case energyIncrease case healthyHabits case looseWeight case relationshipsWithFood } public enum WeightLossFocus: Codable { case activity case healthyHabits c
Replies
0
Boosts
0
Views
470
Activity
Jun ’24
SwiftData filter many to many relationship
my question is how to filter in search text for city.name in Concert ? i tried to reach city name using nested compact map but couldn't handle it. class Concert { var kindOf : String var city : [City] } class City { var name : String @Relationship(inverse: Concert.city) var concert : [Concert] } @Query var concerts : [Concert] @State var searchQuery : String = var filteredConcert : [Concert] { if searchQuery.isEmpty { return concerts } let filteredConcerts = concerts.compactMap { concert in let kindOfContainsSearch = concert.kindOf.range(of: searchQuery) != nil return (kindOfContainsSearch ) ? concert : nil } return filteredConcerts }
Replies
0
Boosts
0
Views
511
Activity
Jan ’24
SwiftData one-to-many Relationship not working
Hello, I have the problem that my todos are not only assigned to one project (one-to-many). They are displayed in the same way in every project. What have I done wrong? Die HauptApp: import SwiftData @main struct consiliaApp: App { var body: some Scene { WindowGroup { ProjektView() }.modelContainer(for: Projekte.self) } } Das Datenmodell: import SwiftData @Model final class Projekte { var name: String var info: String var startdate: Date var enddate: Date var startadresse: String var zieladresse: String var priority: Int @Relationship(deleteRule: .cascade, inverse: Todo.projekte) var todos: [Todo]? = [] init(name: String, info: String, startdate: Date, enddate: Date, startadresse: String, zieladresse: String, priority: Int) { self.name = name self.info = info self.startdate = startdate self.enddate = enddate self.startadresse = startadresse self.zieladresse = zieladresse self.priority = priority } } @Model class Todo { var name: String // @Relationship var projekte: Projekt
Replies
0
Boosts
0
Views
742
Activity
Jan ’24
Reply to XCode 8.1 -> duplicate symbol __TMRbBp
Same problem here when archiving (or compiling release schema), error points to two class with inherit relationship, the strange thing is that it just for specific class, but no luck if only to changed the class name.I empty the class implementation, then the two .o files (for the two classed) are dispear, but two other files (include classes with inherit relationship) are listed in the error.
Replies
Boosts
Views
Activity
Oct ’16
Debugging/Fixing deleted relationship objects with SwiftData
Using SwiftData and this is the simplest example I could boil down: @Model final class Item { var timestamp: Date var tag: Tag? init(timestamp: Date) { self.timestamp = timestamp } } @Model final class Tag { var timestamp: Date init(timestamp: Date) { self.timestamp = timestamp } } Notice Tag has no reference to Item. So if I create a bunch of items and set their Tag. Later on I add the ability to delete a Tag. Since I haven't added inverse relationship Item now references a tag that no longer exists so so I get these types of errors: SwiftData/BackingData.swift:875: Fatal error: This model instance was invalidated because its backing data could no longer be found the store. PersistentIdentifier(id: SwiftData.PersistentIdentifier.ID(url: x-coredata://EEC1D410-F87E-4F1F-B82D-8F2153A0B23C/Tag/p1), implementation: SwiftData.PersistentIdentifierImplementation) I think I understand now that I just need to add the item reference to Tag and SwiftData will nullify all Item referenc
Replies
2
Boosts
0
Views
382
Activity
Mar ’25
SwiftData many-to-many relationship doesn't populate the inverse.
I am using SwiftData in my iOS app and I created 2 models: @Model class Track { // ... var artists: [Artist] // ... init(artists: [Artist] = []) { self.artists = artists } } @Model class Artist { // ... @Relationship(inverse: Track.artists) var tracks: [Track] // ... init() { self.tracks = [] } } And I populate my container like this: // // MyApp.swift // import SwiftUI import SwiftData @main struct NyxApp: App { // TODO: handle exception let container = try! ModelContainer(for: Track.self, Artist.self) var body: some Scene { WindowGroup { ContentView() } .modelContainer(container) } } // // Function to add debug data // { let artist = Artist( // ... ) let track = Track( // ... artists: [artist], // ... ) context.insert(track) try! context.save() } The Track entity stores the Artist in Track.artists temporarily, but when I restart the app, the array is empty. The Artist.tracks array won't even get populated after inserting the track. I didn't find much useful information about many-
Replies
0
Boosts
0
Views
904
Activity
Feb ’24
Reply to SwiftData @Model: Optional to-many relationship is never nil at runtime
SwiftData default store is based on Core Data. As a historical implementation detail, at runtime, a Core Data to-many relationship, once persisted, is always a [], and never a nil. To adapt this behavior in an effective way, SwiftData always initializes a nil to-many relationship with an empty collection at runtime. So to your first question, the behavior that optional to-many relationships in SwiftData are never nil at runtime is as-designed. The requirement that relationships must be optional is a way to express that NSPersistentCloudKitContainer does not handle relationships atomically, and is enforced by a schema validator at compile time. The validation doesn't have any impact at runtime, and so SwiftData to-many relationships being [] at runtime doesn't break the CloudKit synchronization. To use SwiftData + CloudKit, you make sure your model schema is compatible with the rules so the schema validator doesn
Replies
Boosts
Views
Activity
Jan ’26
Reply to Finding source for SwiftData array behaviour
I am not completely clear what your question is, but based on the description, it seems to be related to the order of SwiftData array, and so I'd start with that. In a SwiftData model that contains an array, the array element can be a Codable type or a SwiftData model, as shown below: @Model class Department { @Relationship(deleteRule: .cascade, inverse: Employee.department) var employees: [Employee] = [Employee]() // Relationship var aliasNames: [String] = [] // `String` is Codable ... } @Model class Employee { var department: Department? ... } Here employees is a SwiftData relationship, and aliasNames is an attribute of a string array. Every time you fetch Department and access the attribute and relationship, the elemet order of department.aliasNames is the same, but that of department.employees is not. The reason is that SwiftData uses Core Data as its default store, and in Core Data, a too-many relationship is expres
Topic: UI Frameworks SubTopic: SwiftUI Tags:
Replies
Boosts
Views
Activity
Oct ’25