Search results for

“SwiftData inheritance relationship”

4,986 results found

Post

Replies

Boosts

Views

Activity

Reply to Model instance invalidated, backing data could no longer be found in the store
Update: the problem occurs when the app goes to the background, comes back, and SwiftUI tries to access relationships of SwiftData models that are direct input parameters to the View. My app has a function that opens a URL in a browser, it is when you press the Back button and return from the browser to the app that this fatal error tends to occur. When the app goes to the background, the BackingData of every relationship of this main model seems to get replaced with some subclass of FutureBackingData. Accessing them results in the fatal error above. Explicitly querying the relationship with @Query instead of relying on the relationship property seems to solve the problem. It would be great to have some documentation on how exactly SwiftData is behaving when the app goes to the background.
Topic: Programming Languages SubTopic: Swift Tags:
Dec ’24
Reply to How do I filter @Query with bound item
In your Chore model class, you have the property assignedTo of type FamilyMember. Because you are using SwiftData, an implicit relationship is created. However, in order for the relationship to be complete it needs to have an inverse property in the other model. You need to add a property to FamilyMember that can be that inverse. Here's an example of what it could look like: @Model class Chore { @Relationship(inverse: FamilyMember.chores) var assignedTo: FamilyMember } @Model class FamilyMember { @Relationship var chores: [Chore] } You could remove the Relationship macros and just have that chores property by itself and let SwiftData figure out the relationships, but I haven't tried this yet; it's best to do it yourself, plus you can visually see where the relationships are. In my model classes, relationships are marked as optional, but that's just to satisfy CloudKit. I don't know if they have to be optional regardless
Sep ’23
Swift: How to get the inheritance information from compiled files
the dwarfdump information for a swift .o file does not have the TAG_inheritance, so where is the inheritance information stored for swift files?for something like thisClasses.swift file:class aaaa {}class bbbb: aaaa {}class cccc: bbbb {}I'm trying to get information like below but not from the swift source files. Trying to use nm and dwarfdump or otool etc to get to the information as do not want to parse the swift code files which is harder to do for large projectsbbbb inherits aaaacccc inherits bbbb inherits aaaa
0
0
1.1k
Dec ’18
Compound Indexes with Entity Inheritance
Our data model uses entity inheritance where the top-level entity is abstract and includes the attributes common to all the other (sub)entities. We've trying to improve fetch performance on sub-entities by adding compound indexes but are not getting satisfaction.Examining the sqlite schema shows that there is a single table that includes all attributes from the super-entity plus all attributes form the sub-entities. A sqlite column named z_ent is added by core data and used to identify the applicable sub-entity for a sqlite record.Using sqlite explain query plan on select statements, we've discovered that compound indexes added to a sub-entity are not used, and the only index used is one for z_ent. However we've also discovered that adding the text self to the compound indexes attribute list will create compound indexes in sqlite that include z_ent as well as the other specified attributes, which results in a useful index.The problem is that the generated compound index only includes z_ent when the a
4
0
1.3k
Mar ’17
SwiftData: "Illegal attempt to establish a relationship 'item' between objects in different contexts
I have run into this SwiftData issue in multiple projects and have been able to replicate it by building off of the default SwiftData launch project. The original Item class: class Item { var timestamp: Date init(timestamp: Date) { self.timestamp = timestamp } } New MyItem class to replicate the error. Notice I nest an Item object inside MyItem: class MyItem { var name: String var item: Item init(name: String, item: Item) { self.name = name self.item = item } } I then build off of the default view for a SwiftData project. When the '+' button is pressed, a new list item for both Item and MyItem should appear in their appropriate sections. @Environment(.modelContext) private var modelContext @Query private var items: [Item] @Query private var myItems: [MyItem] var body: some View { NavigationSplitView { List { Section(All Items) { ForEach(items) { item in NavigationLink { Text(Item at (item.timestamp, format: Date.FormatStyle(date: .numeric, time: .standard))) } label: { Text(item.tim
10
0
3.2k
Oct ’23
SwiftData swap two items in a list with relationship
Hi! I have been working on a workout app. I have a model Workout which holds a list of Exercises (EInfo). There can be multiple workouts stored in an app. I am currently trying to create an on move function for a list that shows the exercises in a workout. However, just using a simple swap function does not seem to work. Is there something I am missing? I cant seem to find much information about this @Model class Workout { @Attribute(.unique) var id: UUID var date: Date var name : String var exercises: [EInfo] var isFinished: Bool init(id: UUID = UUID(), date: Date = Date.now, name: String = New Workout, exercises: [EInfo] = [], isFinished: Bool = false) { self.id = id self.date = date self.name = name self.exercises = exercises self.isFinished = isFinished } } @Model class EInfo { @Attribute(.unique) var id: UUID var name: String var sets: [ESet] var orderIndex: Int init(id: UUID = UUID(), name: String = , sets: [ESet] = [ESet()]) { self.id = id self.name = name self.sets = sets self.orderIndex = 0 } func is
0
0
357
Mar ’24
Reply to Changes to SwiftData SubModels do not update the UI
Perhaps try defining a relationship in your models. https://developer.apple.com/documentation/swiftdata/defining-data-relationships-with-enumerations-and-model-classes/ Your current usage of these models is non-standard. I understand that this is a toy example, but it isn't normally done to create a Model inside another Model without defining a relationship between them. You would normally do something like this: import Foundation import SwiftData @Model final class Item { var firstArray: [String] var itemDetail: ItemDetail init(firstArray: [String], itemDetail: ItemDetail) { self.firstArray = firstArray self.itemDetail = itemDetail } } @Model class ItemDetail { var secondArray: [String] // VVV This is the new line that creates the relationship. @Relationship(inverse: Item.itemDetail) var item: Item init(secondArray: [String]) { self.secondArray = secondArray } }
Topic: UI Frameworks SubTopic: SwiftUI Tags:
Aug ’24
SwiftData Migration Error: Missing Attribute Values on Mandatory Relationship
I'm currently working on a data model migration in Swift using a custom schema migration plan. My project involves migrating settings from one schema version to another (SchemaV1 to SchemaV2). Both schema versions include a class named FSViz, but with slightly different properties. In the newer schema, SchemaV2, I introduced a new property named textSettings of type TextSetting, replacing the textColor property from SchemaV1. Here's a simplified version of my migration code and class definitions: Model: extension SchemaV1 { @Model public final class FSViz { @Attribute(.unique) public let id: UUID public var textColor: TextColor init(textColor: TextColor) { self.id = UUID() self.textColor = textColor } } } extension SchemaV2 { @Model public final class FSViz { @Attribute(.unique) public let id: UUID public var textSettings: TextSetting init(textSettings: TextSetting) { self.id = UUID() self.textSettings = textSettings } } } initMyApp: public struct InitMyApp { static func makeInitialFSViz() -> FSViz? { FSVi
1
0
2.4k
Feb ’24
What's the correct way to delete a SwiftData model that is in a many to many relationship?
The deletion is working, but it does not refresh the view. This is similar to a question I asked previously but I started a new test project to try and work this out. @Model class Transaction { var timestamp: Date var note: String @Relationship(deleteRule: .cascade) var items: [Item]? init(timestamp: Date, note: String, items: [Item]? = nil) { self.timestamp = timestamp self.note = note self.items = items } func getModifierCount() -> Int { guard let items = items else { return 0 } return items.reduce(0, {result, item in result + (item.modifiers?.count ?? 0) }) } } @Model class Item { var timestamp: Date var note: String @Relationship(deleteRule: .nullify) var transaction: Transaction? @Relationship(deleteRule: .noAction) var modifiers: [Modifier]? init(timestamp: Date, note: String, transaction: Transaction? = nil, modifiers: [Modifier]? = nil) { self.timestamp = timestamp self.note = note self.transaction = transaction self.modifiers = modifiers } } @Model class Modifier { var t
2
0
867
Apr ’24
Reply to SwiftData and 'Circular references'
Well, my code is crashing with the following error. SwiftData/BackingData.swift:367: Fatal error: Unknown related type - ChildItem My MainItem @Relationship @Relationship(deleteRule: .cascade, originalName: events, inverse: ChildItem.item) var items: [ChildItem]? My ChildItem var item: MainItem? It also crashes when using @Relationship var item: MainItem? for the ChildItem.
Aug ’23
SwiftData: Inserting two entities with same relationship target crashes
I have a Model Class Note: @Model class Note { var id: UUID var created: Date var content: String @Relationship(inverse: Event.notes) var events: [Event]? init(_ content: String, created: Date = .now, events: [Event] = []) { self.id = UUID() self.created = created self.content = content self.events = events } } And Event: @Model class Event: Hashable, Equatable { var id: String var name: String var eventNotes: String? @Relationship var notes: [Note]? // @Transient does not publish (iOS bug?), use .ephemeral instead @Attribute(.ephemeral) var isSelected: Bool = false init(_ name: String = Unnamed Event, calendarId: String, eventNotes: String) { self.id = calendarId self.name = name self.eventNotes = eventNotes } init(from calendarEvent: EKEvent) { self.id = calendarEvent.eventIdentifier self.name = calendarEvent.title self.eventNotes = calendarEvent.notes ?? } ... static func loadEvents(date: Date = Date()) -> [Event] { ... } } I have the following View hierarchy NoteInputView which has @
1
0
1k
Sep ’23
How come NSValidatedUserInterfaceItem doesn't inherit from NSObject protocol?
I never noticed this before, but why doesn't NSValidatedUserInterfaceItem protocol inherit from NSObject? In the validated userInterfaceItem you have to cast to NSObject to do introspection:-(BOOL)validateUserInterfaceItem:(id<NSValidatedUserInterfaceItem>)item { if ([(NSObject*)item isKindOfClass:[NSMenuItem class]]) { } return YES; }Is there ever a case in AppKit where a user interface item would not inherit from NSObject?
Topic: UI Frameworks SubTopic: AppKit Tags:
2
0
555
Sep ’17
Task Isolation Inheritance and SwiftUI
This post discusses a subtlety in Swift concurrency, and specifically how it relates to SwiftUI, that I regularly see confusing folks. I decided to write it up here so that I can link to it rather than explain it repeatedly. If you have a question or a comment, start a new thread and I’ll respond there. Put it in the App & System Services > Processes & Concurrency topic area and tag it with both Swift and Concurrency. Share and Enjoy — Quinn “The Eskimo!” @ Developer Technical Support @ Apple let myEmail = eskimo + 1 + @ + apple.com Task Isolation Inheritance By default, tasks inherit their actor isolation from the surrounding code. This is a common source of confusion. My goal here is to explain why it happens, why it can cause problems, and how to resolve those problems. Imagine you have a main actor class like this: @MainActor class MyClass { var counter: Int = 0 func start() { Task { print(will sleep) doSomeCPUIntensiveWork() print(did sleep) } } } In this example the class is
0
0
3.6k
Aug ’24
Reply to Model instance invalidated, backing data could no longer be found in the store
Update: the problem occurs when the app goes to the background, comes back, and SwiftUI tries to access relationships of SwiftData models that are direct input parameters to the View. My app has a function that opens a URL in a browser, it is when you press the Back button and return from the browser to the app that this fatal error tends to occur. When the app goes to the background, the BackingData of every relationship of this main model seems to get replaced with some subclass of FutureBackingData. Accessing them results in the fatal error above. Explicitly querying the relationship with @Query instead of relying on the relationship property seems to solve the problem. It would be great to have some documentation on how exactly SwiftData is behaving when the app goes to the background.
Topic: Programming Languages SubTopic: Swift Tags:
Replies
Boosts
Views
Activity
Dec ’24
Reply to How do I filter @Query with bound item
In your Chore model class, you have the property assignedTo of type FamilyMember. Because you are using SwiftData, an implicit relationship is created. However, in order for the relationship to be complete it needs to have an inverse property in the other model. You need to add a property to FamilyMember that can be that inverse. Here's an example of what it could look like: @Model class Chore { @Relationship(inverse: FamilyMember.chores) var assignedTo: FamilyMember } @Model class FamilyMember { @Relationship var chores: [Chore] } You could remove the Relationship macros and just have that chores property by itself and let SwiftData figure out the relationships, but I haven't tried this yet; it's best to do it yourself, plus you can visually see where the relationships are. In my model classes, relationships are marked as optional, but that's just to satisfy CloudKit. I don't know if they have to be optional regardless
Replies
Boosts
Views
Activity
Sep ’23
Swift: How to get the inheritance information from compiled files
the dwarfdump information for a swift .o file does not have the TAG_inheritance, so where is the inheritance information stored for swift files?for something like thisClasses.swift file:class aaaa {}class bbbb: aaaa {}class cccc: bbbb {}I'm trying to get information like below but not from the swift source files. Trying to use nm and dwarfdump or otool etc to get to the information as do not want to parse the swift code files which is harder to do for large projectsbbbb inherits aaaacccc inherits bbbb inherits aaaa
Replies
0
Boosts
0
Views
1.1k
Activity
Dec ’18
Compound Indexes with Entity Inheritance
Our data model uses entity inheritance where the top-level entity is abstract and includes the attributes common to all the other (sub)entities. We've trying to improve fetch performance on sub-entities by adding compound indexes but are not getting satisfaction.Examining the sqlite schema shows that there is a single table that includes all attributes from the super-entity plus all attributes form the sub-entities. A sqlite column named z_ent is added by core data and used to identify the applicable sub-entity for a sqlite record.Using sqlite explain query plan on select statements, we've discovered that compound indexes added to a sub-entity are not used, and the only index used is one for z_ent. However we've also discovered that adding the text self to the compound indexes attribute list will create compound indexes in sqlite that include z_ent as well as the other specified attributes, which results in a useful index.The problem is that the generated compound index only includes z_ent when the a
Replies
4
Boosts
0
Views
1.3k
Activity
Mar ’17
SwiftData: "Illegal attempt to establish a relationship 'item' between objects in different contexts
I have run into this SwiftData issue in multiple projects and have been able to replicate it by building off of the default SwiftData launch project. The original Item class: class Item { var timestamp: Date init(timestamp: Date) { self.timestamp = timestamp } } New MyItem class to replicate the error. Notice I nest an Item object inside MyItem: class MyItem { var name: String var item: Item init(name: String, item: Item) { self.name = name self.item = item } } I then build off of the default view for a SwiftData project. When the '+' button is pressed, a new list item for both Item and MyItem should appear in their appropriate sections. @Environment(.modelContext) private var modelContext @Query private var items: [Item] @Query private var myItems: [MyItem] var body: some View { NavigationSplitView { List { Section(All Items) { ForEach(items) { item in NavigationLink { Text(Item at (item.timestamp, format: Date.FormatStyle(date: .numeric, time: .standard))) } label: { Text(item.tim
Replies
10
Boosts
0
Views
3.2k
Activity
Oct ’23
SwiftData swap two items in a list with relationship
Hi! I have been working on a workout app. I have a model Workout which holds a list of Exercises (EInfo). There can be multiple workouts stored in an app. I am currently trying to create an on move function for a list that shows the exercises in a workout. However, just using a simple swap function does not seem to work. Is there something I am missing? I cant seem to find much information about this @Model class Workout { @Attribute(.unique) var id: UUID var date: Date var name : String var exercises: [EInfo] var isFinished: Bool init(id: UUID = UUID(), date: Date = Date.now, name: String = New Workout, exercises: [EInfo] = [], isFinished: Bool = false) { self.id = id self.date = date self.name = name self.exercises = exercises self.isFinished = isFinished } } @Model class EInfo { @Attribute(.unique) var id: UUID var name: String var sets: [ESet] var orderIndex: Int init(id: UUID = UUID(), name: String = , sets: [ESet] = [ESet()]) { self.id = id self.name = name self.sets = sets self.orderIndex = 0 } func is
Replies
0
Boosts
0
Views
357
Activity
Mar ’24
Reply to Changes to SwiftData SubModels do not update the UI
Perhaps try defining a relationship in your models. https://developer.apple.com/documentation/swiftdata/defining-data-relationships-with-enumerations-and-model-classes/ Your current usage of these models is non-standard. I understand that this is a toy example, but it isn't normally done to create a Model inside another Model without defining a relationship between them. You would normally do something like this: import Foundation import SwiftData @Model final class Item { var firstArray: [String] var itemDetail: ItemDetail init(firstArray: [String], itemDetail: ItemDetail) { self.firstArray = firstArray self.itemDetail = itemDetail } } @Model class ItemDetail { var secondArray: [String] // VVV This is the new line that creates the relationship. @Relationship(inverse: Item.itemDetail) var item: Item init(secondArray: [String]) { self.secondArray = secondArray } }
Topic: UI Frameworks SubTopic: SwiftUI Tags:
Replies
Boosts
Views
Activity
Aug ’24
Reply to SwiftData crash when setting child Model to parent
This might help: https://stackoverflow.com/questions/78123958/swiftdata-synced-to-icloud-with-one-to-many-relationship-between-2-models-result
Topic: UI Frameworks SubTopic: SwiftUI Tags:
Replies
Boosts
Views
Activity
Mar ’24
SwiftData Migration Error: Missing Attribute Values on Mandatory Relationship
I'm currently working on a data model migration in Swift using a custom schema migration plan. My project involves migrating settings from one schema version to another (SchemaV1 to SchemaV2). Both schema versions include a class named FSViz, but with slightly different properties. In the newer schema, SchemaV2, I introduced a new property named textSettings of type TextSetting, replacing the textColor property from SchemaV1. Here's a simplified version of my migration code and class definitions: Model: extension SchemaV1 { @Model public final class FSViz { @Attribute(.unique) public let id: UUID public var textColor: TextColor init(textColor: TextColor) { self.id = UUID() self.textColor = textColor } } } extension SchemaV2 { @Model public final class FSViz { @Attribute(.unique) public let id: UUID public var textSettings: TextSetting init(textSettings: TextSetting) { self.id = UUID() self.textSettings = textSettings } } } initMyApp: public struct InitMyApp { static func makeInitialFSViz() -> FSViz? { FSVi
Replies
1
Boosts
0
Views
2.4k
Activity
Feb ’24
What's the correct way to delete a SwiftData model that is in a many to many relationship?
The deletion is working, but it does not refresh the view. This is similar to a question I asked previously but I started a new test project to try and work this out. @Model class Transaction { var timestamp: Date var note: String @Relationship(deleteRule: .cascade) var items: [Item]? init(timestamp: Date, note: String, items: [Item]? = nil) { self.timestamp = timestamp self.note = note self.items = items } func getModifierCount() -> Int { guard let items = items else { return 0 } return items.reduce(0, {result, item in result + (item.modifiers?.count ?? 0) }) } } @Model class Item { var timestamp: Date var note: String @Relationship(deleteRule: .nullify) var transaction: Transaction? @Relationship(deleteRule: .noAction) var modifiers: [Modifier]? init(timestamp: Date, note: String, transaction: Transaction? = nil, modifiers: [Modifier]? = nil) { self.timestamp = timestamp self.note = note self.transaction = transaction self.modifiers = modifiers } } @Model class Modifier { var t
Replies
2
Boosts
0
Views
867
Activity
Apr ’24
Not able to inherit from NSObject in unit test
The following code compiles fine in a normal Swift app, but not in the accompanying unit test bundle. I don't have any idea why. import Foundation struct Dummy: NSObject { // Error: Inheritance from non-protocol type 'NSObject' var name: String? }
Replies
1
Boosts
0
Views
638
Activity
Aug ’23
Reply to SwiftData and 'Circular references'
Well, my code is crashing with the following error. SwiftData/BackingData.swift:367: Fatal error: Unknown related type - ChildItem My MainItem @Relationship @Relationship(deleteRule: .cascade, originalName: events, inverse: ChildItem.item) var items: [ChildItem]? My ChildItem var item: MainItem? It also crashes when using @Relationship var item: MainItem? for the ChildItem.
Replies
Boosts
Views
Activity
Aug ’23
SwiftData: Inserting two entities with same relationship target crashes
I have a Model Class Note: @Model class Note { var id: UUID var created: Date var content: String @Relationship(inverse: Event.notes) var events: [Event]? init(_ content: String, created: Date = .now, events: [Event] = []) { self.id = UUID() self.created = created self.content = content self.events = events } } And Event: @Model class Event: Hashable, Equatable { var id: String var name: String var eventNotes: String? @Relationship var notes: [Note]? // @Transient does not publish (iOS bug?), use .ephemeral instead @Attribute(.ephemeral) var isSelected: Bool = false init(_ name: String = Unnamed Event, calendarId: String, eventNotes: String) { self.id = calendarId self.name = name self.eventNotes = eventNotes } init(from calendarEvent: EKEvent) { self.id = calendarEvent.eventIdentifier self.name = calendarEvent.title self.eventNotes = calendarEvent.notes ?? } ... static func loadEvents(date: Date = Date()) -> [Event] { ... } } I have the following View hierarchy NoteInputView which has @
Replies
1
Boosts
0
Views
1k
Activity
Sep ’23
How come NSValidatedUserInterfaceItem doesn't inherit from NSObject protocol?
I never noticed this before, but why doesn't NSValidatedUserInterfaceItem protocol inherit from NSObject? In the validated userInterfaceItem you have to cast to NSObject to do introspection:-(BOOL)validateUserInterfaceItem:(id<NSValidatedUserInterfaceItem>)item { if ([(NSObject*)item isKindOfClass:[NSMenuItem class]]) { } return YES; }Is there ever a case in AppKit where a user interface item would not inherit from NSObject?
Topic: UI Frameworks SubTopic: AppKit Tags:
Replies
2
Boosts
0
Views
555
Activity
Sep ’17
Task Isolation Inheritance and SwiftUI
This post discusses a subtlety in Swift concurrency, and specifically how it relates to SwiftUI, that I regularly see confusing folks. I decided to write it up here so that I can link to it rather than explain it repeatedly. If you have a question or a comment, start a new thread and I’ll respond there. Put it in the App & System Services > Processes & Concurrency topic area and tag it with both Swift and Concurrency. Share and Enjoy — Quinn “The Eskimo!” @ Developer Technical Support @ Apple let myEmail = eskimo + 1 + @ + apple.com Task Isolation Inheritance By default, tasks inherit their actor isolation from the surrounding code. This is a common source of confusion. My goal here is to explain why it happens, why it can cause problems, and how to resolve those problems. Imagine you have a main actor class like this: @MainActor class MyClass { var counter: Int = 0 func start() { Task { print(will sleep) doSomeCPUIntensiveWork() print(did sleep) } } } In this example the class is
Replies
0
Boosts
0
Views
3.6k
Activity
Aug ’24