Search results for

“SwiftData inheritance relationship”

4,986 results found

Post

Replies

Boosts

Views

Activity

Subclass inheritance
Hi,I am practising subclassing. I have a superclass GameScene and subclass Scene02. I created a scoring that is called in touches began. But when the app transitions to Scene02, the score returns to zero rather than inheriting the score update that is updated in the superclass GameScene init(). How can I make the score in Scene02 class to continue the last score (int 5) from the superclass?Thanks in advanceimport SpriteKitimport GameplayKitclass GameScene: SKScene { var score = 0 let scoreLabel = SKLabelNode(fontNamed: Arial) required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override init(size: CGSize) { super.init(size: size) scoreLabel.fontSize = 35 scoreLabel.text = Score: Score scoreLabel.fontColor = SKColor.black scoreLabel.position = CGPoint(x: scene!.size.width/2.0, y: scene!.size.height/2.0) scoreLabel.zPosition = 5 self.addChild(scoreLabel) updateScore() } override func didMove(to view: SKView) { self.anchorPoint = .zero self.backgroundColor = SKColor.green } func updat
4
0
1.7k
May ’19
SwiftData Model class not triggering observation of computed property that depends on relationship
I created FB13074428 and a small sample project to demonstrate the bug. https://github.com/jamiemcd/Apple-FB13074428 Basically, if a SwiftData class is marked as @Model and it has a computed property that depends on a relationship's stored property, the computed property does not trigger updates in SwiftUI when the underlying relationship changes its stored property. This is Xcode 15 Beta 8. @Model final class Airport { var code: String var name: String var airplanes: [Airplane] init(code: String, name: String, airPlanes: [Airplane]) { self.code = code self.name = name self.airplanes = airPlanes } // Bug: This computed property is not triggering observation in AirportView when airplane.state changes. My understanding of the new observation framework is that it should. var numberOfAirplanesDeparting: Int { var numberOfAirplanesDeparting = 0 for airplane in airplanes { if airplane.state == .departing { numberOfAirplanesDeparting += 1 } } return numberOfAirplanesDeparting } } AirportVi
4
0
2k
Sep ’23
Are TCC permissions inherited by bundled extensions?
Hello, If a user allows access to, for example, Removable Volumes (TCC permission) to the main app, does these permissions will be inherited by a bundled Finder Extension from the main app? More specific, I have an app that bundles a Finder Extension and both the main app and the bundled extension need access to Removable Volumes. Only the main app can request it, since the main app is the only that can prompt the user. If the user allows, will the bundled extension also receive the permissions? If not, is there any workaround? Regards.
1
0
744
Sep ’24
Reply to How to subclass with SwiftData?
first of all, chapeau for the big work, honestly core data was a mess ;) said so: cannot inherit: it's a shame .. if You use class you must allow it, otherwise us struct worse is that you cannot use a class marked with @model in other target where you don't have swiftData available, for example inside an XCTest You got: Thread 1: Fatal error: failed to find a currently active container for SwiftData/ModelContainer.swift:144: Fatal error: failed to find a currently active container for
Oct ’23
Reply to SwiftData: how to reference same model?
The inverse of a SwiftData relationship cannot point back to itself. This is what the circular reference error is referring to. You need to add another property that can be used for the inverse relationship. You don't have to use this property, it's just to satisfy SwiftData's relationship requirements. For example: @Model final class Person { var name = @Relationship(deleteRule: .nullify, inverse: Person.inverseRef) var ref: Person? = nil // Call this whatever you want // Can make private if not using elsewhere @Relationship var inverseRef: Person? } Testing this and adding dump(peter.ref) after deleting cristina yields this output: Optional(Person) ▿ some: Person #0 - _name: Person._SwiftDataNoType ▿ _ref: Optional(Person._SwiftDataNoType()) - some: Person._SwiftDataNoType - _inverseRef: nil ... So peter.ref is not nil but it seems to be an empty model with empty values, essentially nullified. Whether this is the behaviour you want, I don't kno
Topic: UI Frameworks SubTopic: SwiftUI Tags:
Sep ’23
Inheritance Decodable
Hi there,Is there a way to decode a JSON string with model inheritance ?Let's say I have a Parking class thats holds an array of Vehicle ClassesAnd depending on the kind of vehicles, Car or BikeThe Decoder instantiate the right type of vehicle base on some logic (here it would be type: String equal car or bike)Here is a sample jsonlet json = { name: CN Tower, Toronto, vehicles: [{type: car, make: Honda, model: civic},{type: bike, make: Yamaha, model: R6}] } .data(using: .utf8)!A basic example that fill only vehicle classes into my Parkingclass Vehicle: Decodable { let model: String let make: String private let type: String } class Bike: Vehicle {} class Car: Vehicle {} class Parking: Decodable { let name: String let vehicles: [Vehicle] } do { let parking = try JSONDecoder().decode(Parking.self, from: json) dump(parking) } catch let e { dump(e) }So how should I write a nice code that loop trough vehicles during decoding step, then switch on type and instantiate the correct classclass Vehicle: Decodab
1
0
2.5k
Oct ’17
Reply to Complex Swift Data Relationships...
You haven't told us exactly what your issue is but something I spotted with your design that I don't think is correct is the relationship between Teacher and Student. As I see it your design will be simpler and more correct if you complete remove that relationship. A teacher holds (has) one or more classes A student attends (has) one or more classes So indirectly you have the relationship between Teacher and Student via the SchoolClass model. A bit unrelated but I prefer to use the @Relationship macro with the inverted argument for one of the relationship properties since it makes the code clearer for me (and it is also helpful for SwiftData)
Topic: Design SubTopic: General Tags:
Jun ’25
iOS 18 SwiftData Bug: Codable Models Cause Relationship Mapping Error
Here we have yet another bug, I suppose, in SwiftData that happens on iOS18 but it is not an issue on iOS17. There are 2 models defined as follows @Model final public class Note: Identifiable, Codable, Hashable { public private(set) var uuid = UUID().uuidString var heading: String = var tags: [Tag]? init(heading: String = ) { self.heading = heading } required public init(from decoder: Decoder) throws { ... } public func encode(to encoder: Encoder) throws { ... } } @Model final public class Tag: Identifiable, Codable { var name: String = @Relationship(deleteRule: .nullify, inverse: Note.tags) var notes: [Note]? init(_ name: String) { self.name = name } required public init(from decoder: Decoder) throws { … } public func encode(to encoder: Encoder) throws { ... } } and a function o add new tags as follows private func addTags(note: Note, tagNames: [String]) { if note.tags == nil { note.tags = [] } for tagName in tagNames { if let tag = fetchTag(tagName) { if !note.tags!.contains(where: {$0.n
3
0
1.2k
Sep ’24
Module not found when using inheritance
PLATFORM AND VERSION Development environment: Xcode 16.4 (16F6), macOS 15.5 (24F74) Run-time configuration: iOS 18.3.1 DESCRIPTION OF PROBLEM I cannot build my app due to a module not found error when I'm importing Sample-Swift.h header to an ObjectiveC file. I need to use Swift code to ObjectiveC file with Swift code using an external XCFramework. It seems to be related to a mix with ObjectiveC and Swift code when Swift code uses class inheritance from FZWorkoutKit class. With a full Swift project, no issue. STEPS TO REPRODUCE Project https://fizzup.s3.amazonaws.com/files/public/Sample-WK.zip Open the provided project and try to build it. The issue occurs. In MyObject.m file, if you comment the first import (Sample-Swift.h), no issue occurs but I cannot use my Swift code (MyFile class). Uncomment the line commented in step 1. Go to MyFile.swift and change class inheritance from GoModeController (from FZWorkoutKit framework) to UIView (from UIKit). No issue occurs.
0
0
121
Jun ’25
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) { self.name = name self.notes = [] } } @Model final class Note { var name: String var item: Item init(name: String = Note name, item: Item) { self.name = name self.item = item } } @main struct LifeKPIs_SwiftData_PlaygroundApp: App { var body: some Scene { WindowGroup { ContentView() } .modelContainer(for: [Item.self, Note.self]) } } struct ContentView: View { @Environment(.modelContext) private var modelContext var body: some View { //... let item = Item() modelContext.insert(item) //... let note = Note( item: item) //Error here } } Thread 1: Illegal attempt to establish a relationship 'item' between objects in different contexts (source = (entity: Note; id: 0x60000030ef00 x-coredata:///Note/t0C99AC11-423B-4942-9B5D-C9F9E6A4370E7; data: {n item = nil;n name = Note name;n}) , destination = (entity: Item; id: 0xabdd96b5daee15
2
0
1.9k
Aug ’23
Reply to SwiftData: Failed to decode a composite attribute
Hi @Xavier-k , well unfortunately in SwiftData (CoreData for old man as me) things are not so simple. What you have done is change on the model that is used to generate the entity relationships based on SwiftData modelling. What I would like to suggest, even if the modification on model is so simple, is to use a migration strategy from old to new model. For example, this is a great article on argument of SwiftData migration https://www.hackingwithswift.com/quick-start/swiftdata/how-to-create-a-complex-migration-using-versionedschema . SwiftData is not simple... Bye Rob
Nov ’24
Reply to migrating common code to one place
We are getting into object oriented design philosophy here. Describe what those routines do in natural language. If the relationship between your two UIViews and the common stuff is is a, use inheritance to make your two UIView subclasses extend from a common base class. If it's has a, use composition - move the common functionality into a separate class, an instance of which each of your two UIViews would contain.
Jul ’16
Subclass inheritance
Hi,I am practising subclassing. I have a superclass GameScene and subclass Scene02. I created a scoring that is called in touches began. But when the app transitions to Scene02, the score returns to zero rather than inheriting the score update that is updated in the superclass GameScene init(). How can I make the score in Scene02 class to continue the last score (int 5) from the superclass?Thanks in advanceimport SpriteKitimport GameplayKitclass GameScene: SKScene { var score = 0 let scoreLabel = SKLabelNode(fontNamed: Arial) required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override init(size: CGSize) { super.init(size: size) scoreLabel.fontSize = 35 scoreLabel.text = Score: Score scoreLabel.fontColor = SKColor.black scoreLabel.position = CGPoint(x: scene!.size.width/2.0, y: scene!.size.height/2.0) scoreLabel.zPosition = 5 self.addChild(scoreLabel) updateScore() } override func didMove(to view: SKView) { self.anchorPoint = .zero self.backgroundColor = SKColor.green } func updat
Replies
4
Boosts
0
Views
1.7k
Activity
May ’19
SwiftData Model class not triggering observation of computed property that depends on relationship
I created FB13074428 and a small sample project to demonstrate the bug. https://github.com/jamiemcd/Apple-FB13074428 Basically, if a SwiftData class is marked as @Model and it has a computed property that depends on a relationship's stored property, the computed property does not trigger updates in SwiftUI when the underlying relationship changes its stored property. This is Xcode 15 Beta 8. @Model final class Airport { var code: String var name: String var airplanes: [Airplane] init(code: String, name: String, airPlanes: [Airplane]) { self.code = code self.name = name self.airplanes = airPlanes } // Bug: This computed property is not triggering observation in AirportView when airplane.state changes. My understanding of the new observation framework is that it should. var numberOfAirplanesDeparting: Int { var numberOfAirplanesDeparting = 0 for airplane in airplanes { if airplane.state == .departing { numberOfAirplanesDeparting += 1 } } return numberOfAirplanesDeparting } } AirportVi
Replies
4
Boosts
0
Views
2k
Activity
Sep ’23
Are TCC permissions inherited by bundled extensions?
Hello, If a user allows access to, for example, Removable Volumes (TCC permission) to the main app, does these permissions will be inherited by a bundled Finder Extension from the main app? More specific, I have an app that bundles a Finder Extension and both the main app and the bundled extension need access to Removable Volumes. Only the main app can request it, since the main app is the only that can prompt the user. If the user allows, will the bundled extension also receive the permissions? If not, is there any workaround? Regards.
Replies
1
Boosts
0
Views
744
Activity
Sep ’24
Reply to How to subclass with SwiftData?
first of all, chapeau for the big work, honestly core data was a mess ;) said so: cannot inherit: it's a shame .. if You use class you must allow it, otherwise us struct worse is that you cannot use a class marked with @model in other target where you don't have swiftData available, for example inside an XCTest You got: Thread 1: Fatal error: failed to find a currently active container for SwiftData/ModelContainer.swift:144: Fatal error: failed to find a currently active container for
Replies
Boosts
Views
Activity
Oct ’23
Reply to SwiftData: how to reference same model?
The inverse of a SwiftData relationship cannot point back to itself. This is what the circular reference error is referring to. You need to add another property that can be used for the inverse relationship. You don't have to use this property, it's just to satisfy SwiftData's relationship requirements. For example: @Model final class Person { var name = @Relationship(deleteRule: .nullify, inverse: Person.inverseRef) var ref: Person? = nil // Call this whatever you want // Can make private if not using elsewhere @Relationship var inverseRef: Person? } Testing this and adding dump(peter.ref) after deleting cristina yields this output: Optional(Person) ▿ some: Person #0 - _name: Person._SwiftDataNoType ▿ _ref: Optional(Person._SwiftDataNoType()) - some: Person._SwiftDataNoType - _inverseRef: nil ... So peter.ref is not nil but it seems to be an empty model with empty values, essentially nullified. Whether this is the behaviour you want, I don't kno
Topic: UI Frameworks SubTopic: SwiftUI Tags:
Replies
Boosts
Views
Activity
Sep ’23
How to implement an CryptoTokenkit extension by inheriting form TKToken?
Hi, everyone Is there some Sample code or information about implement an CryptoTokenkit extension by inheriting form TKToken and load the extension in the host app? I want to implement an extension with software, but I don't know how to do this. Can anyone give me some help? Thanks very much! Best Regardscd
Replies
1
Boosts
0
Views
746
Activity
Nov ’20
Inheritance Decodable
Hi there,Is there a way to decode a JSON string with model inheritance ?Let's say I have a Parking class thats holds an array of Vehicle ClassesAnd depending on the kind of vehicles, Car or BikeThe Decoder instantiate the right type of vehicle base on some logic (here it would be type: String equal car or bike)Here is a sample jsonlet json = { name: CN Tower, Toronto, vehicles: [{type: car, make: Honda, model: civic},{type: bike, make: Yamaha, model: R6}] } .data(using: .utf8)!A basic example that fill only vehicle classes into my Parkingclass Vehicle: Decodable { let model: String let make: String private let type: String } class Bike: Vehicle {} class Car: Vehicle {} class Parking: Decodable { let name: String let vehicles: [Vehicle] } do { let parking = try JSONDecoder().decode(Parking.self, from: json) dump(parking) } catch let e { dump(e) }So how should I write a nice code that loop trough vehicles during decoding step, then switch on type and instantiate the correct classclass Vehicle: Decodab
Replies
1
Boosts
0
Views
2.5k
Activity
Oct ’17
Failed to Inherit CoreMedia permissions from XXXXXX
Every time I launch my photo editing extension, I'm getting the following error:Failed to inherit CoreMedia permissions from 12501: (null)It happens even when I create a totally new app and brand new extension. I'm running Xcode 7 Beta 4.Has anyone else seen this?
Replies
3
Boosts
0
Views
7.1k
Activity
Jul ’15
Reply to Complex Swift Data Relationships...
You haven't told us exactly what your issue is but something I spotted with your design that I don't think is correct is the relationship between Teacher and Student. As I see it your design will be simpler and more correct if you complete remove that relationship. A teacher holds (has) one or more classes A student attends (has) one or more classes So indirectly you have the relationship between Teacher and Student via the SchoolClass model. A bit unrelated but I prefer to use the @Relationship macro with the inverted argument for one of the relationship properties since it makes the code clearer for me (and it is also helpful for SwiftData)
Topic: Design SubTopic: General Tags:
Replies
Boosts
Views
Activity
Jun ’25
Reply to SwiftData Unexpected type for CompositeAttribute
Questions 1 Why are you using Codable with a @Model type? 2 Why are you not using the SwiftData relationship attribute to define the relationship between foo and some struct or vice versa? If you're transmitting foo or some struct as JSON over the wire, then you shouldn't mix the swift data models with codables.
Replies
Boosts
Views
Activity
Dec ’23
iOS 18 SwiftData Bug: Codable Models Cause Relationship Mapping Error
Here we have yet another bug, I suppose, in SwiftData that happens on iOS18 but it is not an issue on iOS17. There are 2 models defined as follows @Model final public class Note: Identifiable, Codable, Hashable { public private(set) var uuid = UUID().uuidString var heading: String = var tags: [Tag]? init(heading: String = ) { self.heading = heading } required public init(from decoder: Decoder) throws { ... } public func encode(to encoder: Encoder) throws { ... } } @Model final public class Tag: Identifiable, Codable { var name: String = @Relationship(deleteRule: .nullify, inverse: Note.tags) var notes: [Note]? init(_ name: String) { self.name = name } required public init(from decoder: Decoder) throws { … } public func encode(to encoder: Encoder) throws { ... } } and a function o add new tags as follows private func addTags(note: Note, tagNames: [String]) { if note.tags == nil { note.tags = [] } for tagName in tagNames { if let tag = fetchTag(tagName) { if !note.tags!.contains(where: {$0.n
Replies
3
Boosts
0
Views
1.2k
Activity
Sep ’24
Module not found when using inheritance
PLATFORM AND VERSION Development environment: Xcode 16.4 (16F6), macOS 15.5 (24F74) Run-time configuration: iOS 18.3.1 DESCRIPTION OF PROBLEM I cannot build my app due to a module not found error when I'm importing Sample-Swift.h header to an ObjectiveC file. I need to use Swift code to ObjectiveC file with Swift code using an external XCFramework. It seems to be related to a mix with ObjectiveC and Swift code when Swift code uses class inheritance from FZWorkoutKit class. With a full Swift project, no issue. STEPS TO REPRODUCE Project https://fizzup.s3.amazonaws.com/files/public/Sample-WK.zip Open the provided project and try to build it. The issue occurs. In MyObject.m file, if you comment the first import (Sample-Swift.h), no issue occurs but I cannot use my Swift code (MyFile class). Uncomment the line commented in step 1. Go to MyFile.swift and change class inheritance from GoModeController (from FZWorkoutKit framework) to UIView (from UIKit). No issue occurs.
Replies
0
Boosts
0
Views
121
Activity
Jun ’25
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) { self.name = name self.notes = [] } } @Model final class Note { var name: String var item: Item init(name: String = Note name, item: Item) { self.name = name self.item = item } } @main struct LifeKPIs_SwiftData_PlaygroundApp: App { var body: some Scene { WindowGroup { ContentView() } .modelContainer(for: [Item.self, Note.self]) } } struct ContentView: View { @Environment(.modelContext) private var modelContext var body: some View { //... let item = Item() modelContext.insert(item) //... let note = Note( item: item) //Error here } } Thread 1: Illegal attempt to establish a relationship 'item' between objects in different contexts (source = (entity: Note; id: 0x60000030ef00 x-coredata:///Note/t0C99AC11-423B-4942-9B5D-C9F9E6A4370E7; data: {n item = nil;n name = Note name;n}) , destination = (entity: Item; id: 0xabdd96b5daee15
Replies
2
Boosts
0
Views
1.9k
Activity
Aug ’23
Reply to SwiftData: Failed to decode a composite attribute
Hi @Xavier-k , well unfortunately in SwiftData (CoreData for old man as me) things are not so simple. What you have done is change on the model that is used to generate the entity relationships based on SwiftData modelling. What I would like to suggest, even if the modification on model is so simple, is to use a migration strategy from old to new model. For example, this is a great article on argument of SwiftData migration https://www.hackingwithswift.com/quick-start/swiftdata/how-to-create-a-complex-migration-using-versionedschema . SwiftData is not simple... Bye Rob
Replies
Boosts
Views
Activity
Nov ’24
Reply to migrating common code to one place
We are getting into object oriented design philosophy here. Describe what those routines do in natural language. If the relationship between your two UIViews and the common stuff is is a, use inheritance to make your two UIView subclasses extend from a common base class. If it's has a, use composition - move the common functionality into a separate class, an instance of which each of your two UIViews would contain.
Replies
Boosts
Views
Activity
Jul ’16