Search results for

“SwiftData inheritance relationship”

4,982 results found

Post

Replies

Boosts

Views

Activity

SwiftData: how to reference same model?
I have the following model: @Model class Person { var name = @Relationship(deleteRule: .nullify, inverse: Person.ref) var ref: Person? = nil } Now consider the following code: let peter: Person let cristina: Person peter.ref = cristina modelContext.delete(cristina) I would expected that peter.ref is nil, because referenced person was deleted. In reality, this won't even compile due to this error: Circular reference resolving attached macro 'Relationship' If I remove 'inverse' from the relationship it will compile, but it does not do what I need then. So is it possible to have a reference on the model itself with nullify capability? PS Using Xcode 15 beta 7
1
0
1.1k
Aug ’23
How to count rows in SwiftData?
I'm currently writing an app that loads URLs from the HackerNews API. I have implemented Bookmarks by persisting any bookmarked data to SwiftData. I am currently trying to implemented viewed links — i.e. if you click a link, it gets marked as viewed — I was able to do so by persisting the link ID to SwiftData and in each link view, it queries for itself against the existing viewed links, like so: static func viewedPredicate(_ id: Int) -> Predicate { return #Predicate { $0.id == id } } var viewed: [Viewed] { return (try? modelContext.fetch( FetchDescriptor( predicate: ItemView.viewedPredicate(id) ))) ?? [] } But now, I want to provide stats to the user, so I need to count how many viewed links exist. I don't want to return ALL objects from SwiftData, I want a simple Int that tells me how many there are. To do so, I implemented it as follows: private var viewedCount: Int { return (try? modelContext.fetchCount(FetchDescriptor())) ?? 0 } But when I delete the stats, the number does n
1
0
1.3k
Oct ’23
SwiftData Remote Database Updates
I just saw the new SwiftData updates, including the DataStore API. I’m wondering if, in the case of a shared remote datastore, it is possible to enable updates to the model context from the datastore without the model context explicitly requesting them (e.g., through database listeners). If I’m not mistaken, when you use CloudKit with SwiftData, this happens, right?
1
0
559
Jun ’24
Reply to iPadOS 18 Beta and SwiftData issues
I have the exact same issue and just filed a report FB15146262. iOS 18 doesn't set the one-to-many relationship from the 'one' side, i.e. setting student.school = school will actually keep the relationship at nil and can't be saved into context. This is visible in the debugger error message: SwiftData.DefaultStore save failed with error: Error Domain=NSCocoaErrorDomain Code=1570 %{PROPERTY}@ is a required value. UserInfo={NSValidationErrorObject= (entity: Student; id: 0x600000223380 x-coredata://3B392729-2729-4812-B567-647032714A50/Student/t6F58A598-9DC2-4927-A418-8D37D760FC072; data: { name = jack; school = nil; }), NSLocalizedDescription=%{PROPERTY}@ is a required value., NSValidationErrorKey=school, NSValidationErrorValue=null} The workaround by @Rainbowql with additionally calling append fixes this issue on iOS 18 but causes the app to crash on iOS 17, because the relationship is already set normally before calling append. On iOS 17, you will get: SwiftData/PersistentMo
Sep ’24
Reply to How Is `Size` Being Initialized & Accepted as a Parameter, if it's Not in any Subclass nor in the Superclass property, nor '_' is Used Before it?
And last question…In line 20 numberOfSides is literally initialized to 4 (how come, again, it does not have the override keyword, if it's changing the initializer/value from 0 from line 2, to the value of 4?Here also, not an override, you just set the value in the instance of the subclass.So line 20 does not change the value in the superclass. This is a basic principle of inheritance.Logic is:class NamedShape sets a default value of 0 for numberOfSidesWhen you init a Square withclass Square: NamedShape { var sideLength: Double init(sideLength: Double, name: String) { self.sideLength = sideLength super.init(name: name) print(Square inherited numberOfSides, numberOfSides) numberOfSides = 4 }after initializing all properties of the subclass (sideLength, as it was not defined with a default value), you initialize all the properties inherited from super class. super.init means you use the initializer defined in super class.At this point, numberOfSides is 0, for the subclass instance I have added
Topic: Programming Languages SubTopic: Swift Tags:
Apr ’19
Entity.h and Entity.m incorrect import for relationship
Hi! I had an old Core Data Entity, with relationship to AnotherEntity@property(nonatomic, retain) AnotherEntity *anotherEntity;In AnotherEntity.h a have an attribute@property(nonatomic, retain) NSString *title;I've modified some of Entity's attributes (added new one) so after generating new NSManagedObject subclass Xcode generated 4 new classes: Entity.h, Entity.m, Entity+CoreDataProperties.h and Entity+CoreDataProperties.mPreviously AnotherEntity.h had been imported in Entity.h, but this time Xcode imported it in Entity.m. So trying to access entity.anotherEntity.title gives me error Property 'title' cannot be found in forward class objectI've solved it, importing in Entity.h, but wonder if it's correct and Xcode was wrong importing in .m or it's me doing something wrong?
1
0
415
Nov ’15
Tabs with SwiftData
Hello folks, absolute newbie here. I'm following a tutorial that I'm trying to adjust to my own needs. In the tutorial the app is sat up in a way that you can add a new entry to a note taking app by tapping on a button which brings in an edit view. What I'm trying to do is to bring in the edit view by adding it as a tab on the bottom instead. Here's my ContentView: import SwiftData import SwiftUI struct ContentView: View { let example = Entry(content: Example Entry) var body: some View { TabView { LifeEventsView() .tabItem { Label(Life events, systemImage: house) } EditEntryView(entry: example) .tabItem { Label(Add new event, systemImage: plus) } MattersView() .tabItem { Label(What matters, systemImage: house) } } } } #Preview { ContentView() } And here's the EditEntryView: import SwiftData struct EditEntryView: View { @Bindable var entry: Entry var body: some View { Form { TextField(Entry, text: $entry.content, axis: .vertical) } .navigationTitle(Edit entry) .navigationBarTitleDisplayMode(.
0
0
458
Jul ’24
Reply to Fatal error on rollback after delete
I managed to create a minimal repro example: import SwiftData import SwiftUI @Model final class ParentModel { var name: String @Relationship(deleteRule: .cascade, inverse: ChildModel1.parent) var children: [ChildModel1]? @Relationship(deleteRule: .cascade, inverse: ChildModel2.parent) var children2: [ChildModel2]? init(name: String) { self.name = name } } @Model final class ChildModel1 { var name: String @Relationship(deleteRule: .nullify) var parent: ParentModel? init(name: String) { self.name = name } } @Model final class ChildModel2 { var name: String @Relationship(deleteRule: .nullify) var parent: ParentModel? init(name: String) { self.name = name } } struct ContentView: View { @Environment(.modelContext) private var modelContext var body: some View { List { Button(Create parent with children) { createParentWithChildren() } Button(Delete) { delete() } } } func createParentWithChildren() { let parent = ParentModel(name: Parent) let child1 = ChildModel1(name: Chi
1w
If I inherit a class on Xcode do I have to use all of the connections on the subclass that were used on the superclass
So, I am making a quiz game on xcode and I am using 2 classes, ViewController and Progress2ViewController. The ViewController is for the quiz, and the Progress2ViewController is for the progress page after the quiz. Progress2ViewController is a subclass of viewcontroller. My quiz game runs perfectly, then once I get up to the progress section, it crashes with the error message Thread 1: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0), which I assume means that the connections are wrong. So do I have to connect everything from the superclass to the subclass for it to work? I am not very experienced with swift or xcode and this is my first time creating an app. Thank you!
1
0
520
Aug ’17
How do you observe the count of records in a Swift Data relationship?
What is the correct way to track the number of items in a relationship using SwiftData and SwiftUI? Imagine a macOS application with a sidebar that lists Folders and Tags. An Item can belong to a Folder and have many Tags. In the sidebar, I want to show the name of the Folder or Tag along with the number of Items in it. I feel like I'm missing something obvious within SwiftData to wire this up such that my SwiftUI views correctly updated whenever the underlying modelContext is updated. // The basic schema @Model final class Item { var name = Untitled Item var folder: Folder? = nil var tags: [Tag] = [] } @Model final class Folder { var name = Untitled Folder var items: [Item] = [] } @Model final class Tag { var name = Untitled Tag var items: [Item] = [] } // A SwiftUI view to show a Folder. struct FolderRowView: View { let folder: Folder // Should I use an @Query here?? // @Query var items: [Item] var body: some View { HStack { Text(folder.name) Spacer() Text(folder.items.count.forma
1
0
175
Aug ’25
Migration Questions CoreData to SwiftData
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
1
0
1.3k
Jul ’23
I've wondering a no cross-zone relationships.
HI. I've wondering that the CustomZone, no cross-zone relationships has told in Advanced Cloudkit session wwdc'14. but in the situation ,Place ( CKRecord ) in defaultZone, public database or in defaultZone , private databaseand Note (CKRecord ) has a back reference relationship with place id on customZone , private database.is it ok ? I am confusing for myself because Note has relationship with Place about cross-zone (defaultZone in public or private )so is it not good ?and there're another question. Can CKRecordZone have a different-recordtype CKRecord all-in-one?firstly, I think CKRecordZone is like a table (rdbs). so can only have same recordtype. but I think that's not true. so when you create customzone , if one to many modeling data, you can save place , note record in same recordzone. and then also get a atomic-commit function. am I right ?
0
0
292
Jul ’16
SwiftData: how to reference same model?
I have the following model: @Model class Person { var name = @Relationship(deleteRule: .nullify, inverse: Person.ref) var ref: Person? = nil } Now consider the following code: let peter: Person let cristina: Person peter.ref = cristina modelContext.delete(cristina) I would expected that peter.ref is nil, because referenced person was deleted. In reality, this won't even compile due to this error: Circular reference resolving attached macro 'Relationship' If I remove 'inverse' from the relationship it will compile, but it does not do what I need then. So is it possible to have a reference on the model itself with nullify capability? PS Using Xcode 15 beta 7
Replies
1
Boosts
0
Views
1.1k
Activity
Aug ’23
How to fetch entities with several conditions of a to-many relationship met?
How do I fetch entities with a number of different conditions met in a to-many relationship? In other words, if I have an entity Recipient which has a to-many relationship with entity Group, how to I fetch all recipients that are in Group A and B but not in Group C?
Replies
1
Boosts
0
Views
388
Activity
Oct ’17
How to count rows in SwiftData?
I'm currently writing an app that loads URLs from the HackerNews API. I have implemented Bookmarks by persisting any bookmarked data to SwiftData. I am currently trying to implemented viewed links — i.e. if you click a link, it gets marked as viewed — I was able to do so by persisting the link ID to SwiftData and in each link view, it queries for itself against the existing viewed links, like so: static func viewedPredicate(_ id: Int) -> Predicate { return #Predicate { $0.id == id } } var viewed: [Viewed] { return (try? modelContext.fetch( FetchDescriptor( predicate: ItemView.viewedPredicate(id) ))) ?? [] } But now, I want to provide stats to the user, so I need to count how many viewed links exist. I don't want to return ALL objects from SwiftData, I want a simple Int that tells me how many there are. To do so, I implemented it as follows: private var viewedCount: Int { return (try? modelContext.fetchCount(FetchDescriptor())) ?? 0 } But when I delete the stats, the number does n
Replies
1
Boosts
0
Views
1.3k
Activity
Oct ’23
SwiftData Remote Database Updates
I just saw the new SwiftData updates, including the DataStore API. I’m wondering if, in the case of a shared remote datastore, it is possible to enable updates to the model context from the datastore without the model context explicitly requesting them (e.g., through database listeners). If I’m not mistaken, when you use CloudKit with SwiftData, this happens, right?
Replies
1
Boosts
0
Views
559
Activity
Jun ’24
Reply to iPadOS 18 Beta and SwiftData issues
I have the exact same issue and just filed a report FB15146262. iOS 18 doesn't set the one-to-many relationship from the 'one' side, i.e. setting student.school = school will actually keep the relationship at nil and can't be saved into context. This is visible in the debugger error message: SwiftData.DefaultStore save failed with error: Error Domain=NSCocoaErrorDomain Code=1570 %{PROPERTY}@ is a required value. UserInfo={NSValidationErrorObject= (entity: Student; id: 0x600000223380 x-coredata://3B392729-2729-4812-B567-647032714A50/Student/t6F58A598-9DC2-4927-A418-8D37D760FC072; data: { name = jack; school = nil; }), NSLocalizedDescription=%{PROPERTY}@ is a required value., NSValidationErrorKey=school, NSValidationErrorValue=null} The workaround by @Rainbowql with additionally calling append fixes this issue on iOS 18 but causes the app to crash on iOS 17, because the relationship is already set normally before calling append. On iOS 17, you will get: SwiftData/PersistentMo
Replies
Boosts
Views
Activity
Sep ’24
Reply to How Is `Size` Being Initialized & Accepted as a Parameter, if it's Not in any Subclass nor in the Superclass property, nor '_' is Used Before it?
And last question…In line 20 numberOfSides is literally initialized to 4 (how come, again, it does not have the override keyword, if it's changing the initializer/value from 0 from line 2, to the value of 4?Here also, not an override, you just set the value in the instance of the subclass.So line 20 does not change the value in the superclass. This is a basic principle of inheritance.Logic is:class NamedShape sets a default value of 0 for numberOfSidesWhen you init a Square withclass Square: NamedShape { var sideLength: Double init(sideLength: Double, name: String) { self.sideLength = sideLength super.init(name: name) print(Square inherited numberOfSides, numberOfSides) numberOfSides = 4 }after initializing all properties of the subclass (sideLength, as it was not defined with a default value), you initialize all the properties inherited from super class. super.init means you use the initializer defined in super class.At this point, numberOfSides is 0, for the subclass instance I have added
Topic: Programming Languages SubTopic: Swift Tags:
Replies
Boosts
Views
Activity
Apr ’19
Is SwiftData created specifically for SwiftUI?
Many of Apple's tutorials on SwiftData are written alongside SwiftUI, including the sample code. Would it be a bad idea to use SwiftData separately? If I don't use SwiftUI, would it be wiser to choose a different database instead?
Replies
2
Boosts
0
Views
455
Activity
Apr ’24
Entity.h and Entity.m incorrect import for relationship
Hi! I had an old Core Data Entity, with relationship to AnotherEntity@property(nonatomic, retain) AnotherEntity *anotherEntity;In AnotherEntity.h a have an attribute@property(nonatomic, retain) NSString *title;I've modified some of Entity's attributes (added new one) so after generating new NSManagedObject subclass Xcode generated 4 new classes: Entity.h, Entity.m, Entity+CoreDataProperties.h and Entity+CoreDataProperties.mPreviously AnotherEntity.h had been imported in Entity.h, but this time Xcode imported it in Entity.m. So trying to access entity.anotherEntity.title gives me error Property 'title' cannot be found in forward class objectI've solved it, importing in Entity.h, but wonder if it's correct and Xcode was wrong importing in .m or it's me doing something wrong?
Replies
1
Boosts
0
Views
415
Activity
Nov ’15
Tabs with SwiftData
Hello folks, absolute newbie here. I'm following a tutorial that I'm trying to adjust to my own needs. In the tutorial the app is sat up in a way that you can add a new entry to a note taking app by tapping on a button which brings in an edit view. What I'm trying to do is to bring in the edit view by adding it as a tab on the bottom instead. Here's my ContentView: import SwiftData import SwiftUI struct ContentView: View { let example = Entry(content: Example Entry) var body: some View { TabView { LifeEventsView() .tabItem { Label(Life events, systemImage: house) } EditEntryView(entry: example) .tabItem { Label(Add new event, systemImage: plus) } MattersView() .tabItem { Label(What matters, systemImage: house) } } } } #Preview { ContentView() } And here's the EditEntryView: import SwiftData struct EditEntryView: View { @Bindable var entry: Entry var body: some View { Form { TextField(Entry, text: $entry.content, axis: .vertical) } .navigationTitle(Edit entry) .navigationBarTitleDisplayMode(.
Replies
0
Boosts
0
Views
458
Activity
Jul ’24
Reply to Fatal error on rollback after delete
I managed to create a minimal repro example: import SwiftData import SwiftUI @Model final class ParentModel { var name: String @Relationship(deleteRule: .cascade, inverse: ChildModel1.parent) var children: [ChildModel1]? @Relationship(deleteRule: .cascade, inverse: ChildModel2.parent) var children2: [ChildModel2]? init(name: String) { self.name = name } } @Model final class ChildModel1 { var name: String @Relationship(deleteRule: .nullify) var parent: ParentModel? init(name: String) { self.name = name } } @Model final class ChildModel2 { var name: String @Relationship(deleteRule: .nullify) var parent: ParentModel? init(name: String) { self.name = name } } struct ContentView: View { @Environment(.modelContext) private var modelContext var body: some View { List { Button(Create parent with children) { createParentWithChildren() } Button(Delete) { delete() } } } func createParentWithChildren() { let parent = ParentModel(name: Parent) let child1 = ChildModel1(name: Chi
Replies
Boosts
Views
Activity
1w
Reply to Why I don't like implicit self. in classes
Why sad from inheriting from the correct class?
Topic: Programming Languages SubTopic: Swift Tags:
Replies
Boosts
Views
Activity
Jul ’15
If I inherit a class on Xcode do I have to use all of the connections on the subclass that were used on the superclass
So, I am making a quiz game on xcode and I am using 2 classes, ViewController and Progress2ViewController. The ViewController is for the quiz, and the Progress2ViewController is for the progress page after the quiz. Progress2ViewController is a subclass of viewcontroller. My quiz game runs perfectly, then once I get up to the progress section, it crashes with the error message Thread 1: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0), which I assume means that the connections are wrong. So do I have to connect everything from the superclass to the subclass for it to work? I am not very experienced with swift or xcode and this is my first time creating an app. Thank you!
Replies
1
Boosts
0
Views
520
Activity
Aug ’17
How do you observe the count of records in a Swift Data relationship?
What is the correct way to track the number of items in a relationship using SwiftData and SwiftUI? Imagine a macOS application with a sidebar that lists Folders and Tags. An Item can belong to a Folder and have many Tags. In the sidebar, I want to show the name of the Folder or Tag along with the number of Items in it. I feel like I'm missing something obvious within SwiftData to wire this up such that my SwiftUI views correctly updated whenever the underlying modelContext is updated. // The basic schema @Model final class Item { var name = Untitled Item var folder: Folder? = nil var tags: [Tag] = [] } @Model final class Folder { var name = Untitled Folder var items: [Item] = [] } @Model final class Tag { var name = Untitled Tag var items: [Item] = [] } // A SwiftUI view to show a Folder. struct FolderRowView: View { let folder: Folder // Should I use an @Query here?? // @Query var items: [Item] var body: some View { HStack { Text(folder.name) Spacer() Text(folder.items.count.forma
Replies
1
Boosts
0
Views
175
Activity
Aug ’25
Migration Questions CoreData to SwiftData
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
Replies
1
Boosts
0
Views
1.3k
Activity
Jul ’23
I've wondering a no cross-zone relationships.
HI. I've wondering that the CustomZone, no cross-zone relationships has told in Advanced Cloudkit session wwdc'14. but in the situation ,Place ( CKRecord ) in defaultZone, public database or in defaultZone , private databaseand Note (CKRecord ) has a back reference relationship with place id on customZone , private database.is it ok ? I am confusing for myself because Note has relationship with Place about cross-zone (defaultZone in public or private )so is it not good ?and there're another question. Can CKRecordZone have a different-recordtype CKRecord all-in-one?firstly, I think CKRecordZone is like a table (rdbs). so can only have same recordtype. but I think that's not true. so when you create customzone , if one to many modeling data, you can save place , note record in same recordzone. and then also get a atomic-commit function. am I right ?
Replies
0
Boosts
0
Views
292
Activity
Jul ’16