Search results for

“SwiftData inheritance relationship”

4,982 results found

Post

Replies

Boosts

Views

Activity

Reply to Subclassing a class that has convenience initializers.
If you override all of the superclass designated initializers, you'll inherit the superclass convenience initializers. (See Swift docs, Initialization -> Automatic Initializer Inheritance -> Rule 2.) I think in this case that means you can define an init(property1:) that just calls through to super and you should able to use init(value1:value2) for subclass initialization.
Topic: Programming Languages SubTopic: Swift Tags:
Jan ’16
Reply to Too many empty "required" UIView.init(coder:) methods
In the last example, that happens because you haven't overridden all of the designated inits — just init() in this case — and therefore you do not inherit the superclass convenience initializers — that is init(coder:). The earlier MyView2 is fine because it overrides all designated inits — again just init() — and so it does inherit convenience inits. All of this is a consequence of the init inheritance rules documented in the Swift language guide.In the MyView1 case, I think problem is that your re-definition of init prevents automatic inheritance, so you don't need init(frame:) but you still need init(coder:) to satisfy the required keyword in the NSCoding protocol.Like I said, it would probably be easier to provide the intermediate class in Obj-C, so that you could break the rules without being reprimanded by the compiler, but the easiest approach is to forget the intermediate classes and just provide a init(coder:) when the compiler insists.
Topic: UI Frameworks SubTopic: UIKit Tags:
Mar ’17
SwiftData Predicate with "format:"
Hi, if you have an array of object IDs, with CoreData you can fetch all of the objects for those IDs at once with the right predicate. It would look something like this: let objectIDs: [NSManagedObjectID] = [id1,id2,id3,id4] let predicate = NSPredicate(format: self in %@, objectIDs) Can something similar be created with a SwiftData predicate? For now I fetch all ids one by one and as you might guess, performance wise this is not great.
0
0
587
Feb ’24
Reply to Mac App Crashing with Illegal Instructions
After some digging I found out that SwiftData is causing the problem. More concrete relationships I have a class Account with has (optional) categories @Relationship(deleteRule: .cascade, inverse: Category.account) var _categories: [Category]? var categories: [Category] { self._categories ?? [] } in the class Category I have the a simple account variable var account: Account The application crahses when I use the following init function in Account (at the last line) init(id: Int, income: Bool, location: String, maintainance: Bool, special: Bool, taxRate: Float, tenant: String, title: String) { self.id = id self.income = income self.location = location self.maintainance = maintainance self.special = special self.taxRate = taxRate self.tenant = tenant self.title = title self._categories = [] } or when I use those lines // category not found, so create one let category: Category = Category(title: categoryName, account: self) if self._categories == nil { self._categories = [category] }
Apr ’25
SwiftData in background task
I wrote this simple app to try to fetch and add data to my airport Database in the background. I'm trying to add some data to the airport table in the background using swift-data, I create a loop that should add and save 100 test airports in a table but when I run the code I only get add 1 airport at the time and the number get add is random, any idea why? How to use swiftData in the background? So far not so many examples. actor JsonImporter: ModelActor { let executor: any ModelExecutor let context: ModelContext init(modelContainer: ModelContainer) { context = ModelContext(modelContainer) executor = DefaultModelExecutor(context: context) } func parseJsonDBAirport() async { for i in 1...100{ print(loop (i)) let airport = Airport(lastPicked: Date(), icao: test (i)) context.insert(airport) do{ try context.save() }catch { print(Error) } } } } Using on the view: struct SettingsView: View { @Environment (.modelContext) var mc var body: some View { Button { Task(priority: .background){ let importer = JsonI
0
0
1.5k
Jul ’23
SwiftData Multiple ModelConfigurations
A ModelContainer with two configurations for two seperate models with one set to isStoredInMemoryOnly:false and the other one isStoredInMemoryOnly:true crashes after insertion. Anyone git this to work? import SwiftData @main struct RecipeBookApp: App { var container: ModelContainer init() { do { let config1 = ModelConfiguration(for: Recipe.self) let config2 = ModelConfiguration(for: Comment.self, isStoredInMemoryOnly: true) container = try ModelContainer(for: Recipe.self, Comment.self, configurations: config1, config2) } catch { fatalError(Failed to configure SwiftData container.) } } var body: some Scene { WindowGroup { ContentView() .modelContainer(container) } } } struct ContentView: View { @Environment(.modelContext) private var context @Query private var recipes: [Recipe] @Query private var comments: [Comment] var body: some View { VStack { Button(Insert) { context.insert(Recipe(name:Test)) context.insert(Comment(name:Test)) } List(recipes){ recipe in Text(recipe.name) } List(comments){
2
0
1.5k
Sep ’24
SwiftData deleteRule .cascade
I made simple school & student model with RelationShip import SwiftUI import SwiftData @Model final class School { var name: String @Relationship(deleteRule: .cascade, inverse: Student.school) var studentList: [Student] = [Student]() init(name: String) { self.name = name } } @Model final class Student { var name: String var school: School? init(name: String) { self.name = name } } ~ struct SchoolView: View { @Environment(.modelContext) private var modelContext @Query(sort: School.name) var schools: [School] @Query(sort: Student.name) var students: [Student] var body: some View { NavigationStack { List { ForEach(schools) { school in NavigationLink { StudentView(school: school) } label: { HStack { Text(school.name) Spacer() Text((school.studentList.count)) } } .swipeActions { Button(role: .destructive) { deleteSchool(school) } label: { Label(Delete, systemImage: trash) } } } .onDelete(perform: deleteSchools(at:)) } .navigationTitle(Home) .listStyle(.plain) .toolbar { ToolbarItem(p
0
0
788
Nov ’23
Reply to Protocol extension dispatch anomalies
I dunno, but it looks like it might be the same thing as this:https://forums.developer.apple.com/thread/11126Specifically, there's something like inheritance that's supposed to be going on here, but it isn't like any kind of inheritance that we know elsewhere in the language. It may be a bug, or it may be a limitation.My example was reported as bug #21885544, if you're inclined to report yours as a duplicate.
Topic: Programming Languages SubTopic: Swift Tags:
Jul ’15
What is the affection of insert order in SwiftData
In SwiftData, what is the order of insertion for dependent and parent instances? In the snippet below, it works when the dependent instance is inserted before the parent. However, it fails when the order is reversed. Why is this the case? // // DebugView.swift // gogodict // // Created by djzhu on 2024/1/13. // import Foundation import SwiftData import SwiftUI struct DebugView: View { @Query var parent: [ParentClass] @Query var dept: [DependentClass] var body: some View { Text(parent cnt:(parent.count), dept cnt:(dept.count)) } } @Model class ParentClass { @Relationship(deleteRule: .cascade) var deps: DependentClass init(deps: DependentClass) { self.deps = deps } } @Model class DependentClass { var id: String init(id: String = UUID().uuidString) { self.id = id } } #Preview { do { let config = ModelConfiguration(isStoredInMemoryOnly: true) let container = try ModelContainer(for: ParentClass.self, configurations: config) let context = ModelContext(container) var dept = DependentClass(
0
0
526
Jan ’24
SwiftData & CloudKit: Deduplication Logic
I followed these two resources and setup history tracking in SwiftData. SwiftData History tracking: Track model changes with SwiftData history For data deduplication: Sharing Core Data objects between iCloud users In the sample app (CoreDataCloudKitShare), a uuid: UUID field is used for deduplication logic. It sorts the entities by their uuids, reserves the first one, and marks the others as deduplicated. Would it be a viable solution to use a createdAt: Date field for the sort operation instead of a uuid field, or are dates inherently problematic?
4
0
994
Jan ’25
swiftData slow with large data
My database has over 100k entries and anytime I access it either via @Query or a custom Fetch request it freezes my apps UI for 10+ second. My first question is anyone having performance issues with large data sets. If so how have you found to resolve it ? My next question is does swiftUI load the entire database into memory with the @Query. As I feel it is seeing as my app becomes very slow and partially unresponsive. lastly if I have 2 data models and 1 has a to many relationship to the other are both loaded into memory even though only @Query 1? consider datamodels model1 { var name : String @Relationship(deleteRule:.cascade) var lotsOfData :[LotsOfData] init.... } LotsOfData{ var element1 : String var element2 : String var element3 : String var element4 : String var element4 : String init …. } LotsOfData has 100K instances in the database. if I @Query into model1 because it references LotsOfData through A relationship is all that data all called / loaded ? thanks for the informa
1
0
2.2k
Oct ’23
Multiple entities relationship with shop customers vehicle
How can I connect multiple identities with no common sharing fields between them into one object? Also what would be the relationship between these identities? Do I need to add a field called ID for each like CUSTID or ShopID or whatever to my struct that I built? Also I want to put them all in separate array obj for example customer struct with its properties will be stored in customer = [Customer] () How do I store and access them from a custom cell with label and textfield in a tableviewcontroller so that they all attach together as one object with shop and with techninfo shopinfo and with inspectionitems. I am a new programmer trying to do my project on my own and my concept need some clarification so I can move forward with it and get this app done. Please help if you can ...any help will be appreciated.
0
0
335
Oct ’21
SwiftData "Batch Delete" Fails With NSCoreDataOptimisticLockingFailure
I am trying to use the ModelContainer's delete function to delete all instances of a model but I'm getting an error related to my relationships: Constraint trigger violation: Batch delete failed due to mandatory OTO nullify inverse on LeagueSeasonRanking/golfer I do have a relationship on Golfer, a toMany relationship to LeagueSeasonRanking which is marked with a cascade delete rule... I would expect that to take care of things and cascade along but it seems to not work. Is that a bug?
0
0
579
Aug ’24
Reply to Subclassing a class that has convenience initializers.
If you override all of the superclass designated initializers, you'll inherit the superclass convenience initializers. (See Swift docs, Initialization -> Automatic Initializer Inheritance -> Rule 2.) I think in this case that means you can define an init(property1:) that just calls through to super and you should able to use init(value1:value2) for subclass initialization.
Topic: Programming Languages SubTopic: Swift Tags:
Replies
Boosts
Views
Activity
Jan ’16
Reply to Too many empty "required" UIView.init(coder:) methods
In the last example, that happens because you haven't overridden all of the designated inits — just init() in this case — and therefore you do not inherit the superclass convenience initializers — that is init(coder:). The earlier MyView2 is fine because it overrides all designated inits — again just init() — and so it does inherit convenience inits. All of this is a consequence of the init inheritance rules documented in the Swift language guide.In the MyView1 case, I think problem is that your re-definition of init prevents automatic inheritance, so you don't need init(frame:) but you still need init(coder:) to satisfy the required keyword in the NSCoding protocol.Like I said, it would probably be easier to provide the intermediate class in Obj-C, so that you could break the rules without being reprimanded by the compiler, but the easiest approach is to forget the intermediate classes and just provide a init(coder:) when the compiler insists.
Topic: UI Frameworks SubTopic: UIKit Tags:
Replies
Boosts
Views
Activity
Mar ’17
macOS swiftData Delete item
I downloaded X-Code Beta and selected macOS app and swiftData. The template that opens allows you to add items but the delete function built in doesn't seem to work. Has anyone come up with a solution?
Replies
1
Boosts
0
Views
477
Activity
Sep ’23
SwiftData Predicate with "format:"
Hi, if you have an array of object IDs, with CoreData you can fetch all of the objects for those IDs at once with the right predicate. It would look something like this: let objectIDs: [NSManagedObjectID] = [id1,id2,id3,id4] let predicate = NSPredicate(format: self in %@, objectIDs) Can something similar be created with a SwiftData predicate? For now I fetch all ids one by one and as you might guess, performance wise this is not great.
Replies
0
Boosts
0
Views
587
Activity
Feb ’24
Reply to Mac App Crashing with Illegal Instructions
After some digging I found out that SwiftData is causing the problem. More concrete relationships I have a class Account with has (optional) categories @Relationship(deleteRule: .cascade, inverse: Category.account) var _categories: [Category]? var categories: [Category] { self._categories ?? [] } in the class Category I have the a simple account variable var account: Account The application crahses when I use the following init function in Account (at the last line) init(id: Int, income: Bool, location: String, maintainance: Bool, special: Bool, taxRate: Float, tenant: String, title: String) { self.id = id self.income = income self.location = location self.maintainance = maintainance self.special = special self.taxRate = taxRate self.tenant = tenant self.title = title self._categories = [] } or when I use those lines // category not found, so create one let category: Category = Category(title: categoryName, account: self) if self._categories == nil { self._categories = [category] }
Replies
Boosts
Views
Activity
Apr ’25
SwiftData in background task
I wrote this simple app to try to fetch and add data to my airport Database in the background. I'm trying to add some data to the airport table in the background using swift-data, I create a loop that should add and save 100 test airports in a table but when I run the code I only get add 1 airport at the time and the number get add is random, any idea why? How to use swiftData in the background? So far not so many examples. actor JsonImporter: ModelActor { let executor: any ModelExecutor let context: ModelContext init(modelContainer: ModelContainer) { context = ModelContext(modelContainer) executor = DefaultModelExecutor(context: context) } func parseJsonDBAirport() async { for i in 1...100{ print(loop (i)) let airport = Airport(lastPicked: Date(), icao: test (i)) context.insert(airport) do{ try context.save() }catch { print(Error) } } } } Using on the view: struct SettingsView: View { @Environment (.modelContext) var mc var body: some View { Button { Task(priority: .background){ let importer = JsonI
Replies
0
Boosts
0
Views
1.5k
Activity
Jul ’23
Merge One to One Relationship Into Single Entity
I have two entities, Highlight and Location, that have a one-to-one relationship with each other. Location has just 2 properties, start and end. There is no longer any reason for Highlight and Location to be separate and I would like to just merge it all onto Highlight. Is this possible to do a migration (e.g., mapping model)?
Replies
0
Boosts
0
Views
500
Activity
Jun ’21
SwiftData Multiple ModelConfigurations
A ModelContainer with two configurations for two seperate models with one set to isStoredInMemoryOnly:false and the other one isStoredInMemoryOnly:true crashes after insertion. Anyone git this to work? import SwiftData @main struct RecipeBookApp: App { var container: ModelContainer init() { do { let config1 = ModelConfiguration(for: Recipe.self) let config2 = ModelConfiguration(for: Comment.self, isStoredInMemoryOnly: true) container = try ModelContainer(for: Recipe.self, Comment.self, configurations: config1, config2) } catch { fatalError(Failed to configure SwiftData container.) } } var body: some Scene { WindowGroup { ContentView() .modelContainer(container) } } } struct ContentView: View { @Environment(.modelContext) private var context @Query private var recipes: [Recipe] @Query private var comments: [Comment] var body: some View { VStack { Button(Insert) { context.insert(Recipe(name:Test)) context.insert(Comment(name:Test)) } List(recipes){ recipe in Text(recipe.name) } List(comments){
Replies
2
Boosts
0
Views
1.5k
Activity
Sep ’24
SwiftData deleteRule .cascade
I made simple school & student model with RelationShip import SwiftUI import SwiftData @Model final class School { var name: String @Relationship(deleteRule: .cascade, inverse: Student.school) var studentList: [Student] = [Student]() init(name: String) { self.name = name } } @Model final class Student { var name: String var school: School? init(name: String) { self.name = name } } ~ struct SchoolView: View { @Environment(.modelContext) private var modelContext @Query(sort: School.name) var schools: [School] @Query(sort: Student.name) var students: [Student] var body: some View { NavigationStack { List { ForEach(schools) { school in NavigationLink { StudentView(school: school) } label: { HStack { Text(school.name) Spacer() Text((school.studentList.count)) } } .swipeActions { Button(role: .destructive) { deleteSchool(school) } label: { Label(Delete, systemImage: trash) } } } .onDelete(perform: deleteSchools(at:)) } .navigationTitle(Home) .listStyle(.plain) .toolbar { ToolbarItem(p
Replies
0
Boosts
0
Views
788
Activity
Nov ’23
Reply to Protocol extension dispatch anomalies
I dunno, but it looks like it might be the same thing as this:https://forums.developer.apple.com/thread/11126Specifically, there's something like inheritance that's supposed to be going on here, but it isn't like any kind of inheritance that we know elsewhere in the language. It may be a bug, or it may be a limitation.My example was reported as bug #21885544, if you're inclined to report yours as a duplicate.
Topic: Programming Languages SubTopic: Swift Tags:
Replies
Boosts
Views
Activity
Jul ’15
What is the affection of insert order in SwiftData
In SwiftData, what is the order of insertion for dependent and parent instances? In the snippet below, it works when the dependent instance is inserted before the parent. However, it fails when the order is reversed. Why is this the case? // // DebugView.swift // gogodict // // Created by djzhu on 2024/1/13. // import Foundation import SwiftData import SwiftUI struct DebugView: View { @Query var parent: [ParentClass] @Query var dept: [DependentClass] var body: some View { Text(parent cnt:(parent.count), dept cnt:(dept.count)) } } @Model class ParentClass { @Relationship(deleteRule: .cascade) var deps: DependentClass init(deps: DependentClass) { self.deps = deps } } @Model class DependentClass { var id: String init(id: String = UUID().uuidString) { self.id = id } } #Preview { do { let config = ModelConfiguration(isStoredInMemoryOnly: true) let container = try ModelContainer(for: ParentClass.self, configurations: config) let context = ModelContext(container) var dept = DependentClass(
Replies
0
Boosts
0
Views
526
Activity
Jan ’24
SwiftData & CloudKit: Deduplication Logic
I followed these two resources and setup history tracking in SwiftData. SwiftData History tracking: Track model changes with SwiftData history For data deduplication: Sharing Core Data objects between iCloud users In the sample app (CoreDataCloudKitShare), a uuid: UUID field is used for deduplication logic. It sorts the entities by their uuids, reserves the first one, and marks the others as deduplicated. Would it be a viable solution to use a createdAt: Date field for the sort operation instead of a uuid field, or are dates inherently problematic?
Replies
4
Boosts
0
Views
994
Activity
Jan ’25
swiftData slow with large data
My database has over 100k entries and anytime I access it either via @Query or a custom Fetch request it freezes my apps UI for 10+ second. My first question is anyone having performance issues with large data sets. If so how have you found to resolve it ? My next question is does swiftUI load the entire database into memory with the @Query. As I feel it is seeing as my app becomes very slow and partially unresponsive. lastly if I have 2 data models and 1 has a to many relationship to the other are both loaded into memory even though only @Query 1? consider datamodels model1 { var name : String @Relationship(deleteRule:.cascade) var lotsOfData :[LotsOfData] init.... } LotsOfData{ var element1 : String var element2 : String var element3 : String var element4 : String var element4 : String init …. } LotsOfData has 100K instances in the database. if I @Query into model1 because it references LotsOfData through A relationship is all that data all called / loaded ? thanks for the informa
Replies
1
Boosts
0
Views
2.2k
Activity
Oct ’23
Multiple entities relationship with shop customers vehicle
How can I connect multiple identities with no common sharing fields between them into one object? Also what would be the relationship between these identities? Do I need to add a field called ID for each like CUSTID or ShopID or whatever to my struct that I built? Also I want to put them all in separate array obj for example customer struct with its properties will be stored in customer = [Customer] () How do I store and access them from a custom cell with label and textfield in a tableviewcontroller so that they all attach together as one object with shop and with techninfo shopinfo and with inspectionitems. I am a new programmer trying to do my project on my own and my concept need some clarification so I can move forward with it and get this app done. Please help if you can ...any help will be appreciated.
Replies
0
Boosts
0
Views
335
Activity
Oct ’21
SwiftData "Batch Delete" Fails With NSCoreDataOptimisticLockingFailure
I am trying to use the ModelContainer's delete function to delete all instances of a model but I'm getting an error related to my relationships: Constraint trigger violation: Batch delete failed due to mandatory OTO nullify inverse on LeagueSeasonRanking/golfer I do have a relationship on Golfer, a toMany relationship to LeagueSeasonRanking which is marked with a cascade delete rule... I would expect that to take care of things and cascade along but it seems to not work. Is that a bug?
Replies
0
Boosts
0
Views
579
Activity
Aug ’24