Search results for

“SwiftData inheritance relationship”

4,982 results found

Post

Replies

Boosts

Views

Activity

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 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 Once my core data model is set up, how do I then instantiate objects that follow the hierarchy tree?
First, you'll have a better chance of getting answers if you move this question to the Core Data or Cocoa sections of the forum. The Core Data and Cocoa sections are in the App Frameworks section of the developer forums.To answer your question about what project an ObjectA belongs to, add relationships to your Core Data model. Your Project entity would have a relationship for its ObjectA items. The destination for this relationship is ObjectA. Your ObjectA entity would have a relationship for its project whose destination is Project. Each relationship is the inverse of the other relationship.The relationships for ObjectA and ObjectB are similar. Create a second relationship for ObjectA for its ObjectB items. Create a relationship for the ObjectB entity for the ObjectA it belongs to. These two relationships are the inverses of each other.In code the relationships are just variables. The project relationship for O
Sep ’17
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
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
SwiftData Unexpected type for CompositeAttribute
I'm getting SwiftData/SchemaProperty.swift:369: Fatal error: Unexpected type for CompositeAttribute CLLocationCoordinate2D in the following situation - this is simplified, but demonstrates the issue. There are a lot of posts discussing Measurements running into the same issue, and the recommended fix is to turn the Measurement (or CLLocationCoordinate2D in this example) into a computed property and generate it on the fly. I'm trying to cache instances of CLLocationCoordinate2D, rather than creating new ones every time a View renders, so those work arounds don't work around. The SwiftData docs seem to indicate that this should be possible. Can anyone recommend a fix? Thanks in advance. import SwiftData import MapKit @Model final class foo : Codable { var bar: SomeStruct init( bar: SomeStruct ) { self.bar = bar } enum CodingKeys : CodingKey { case bar } init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) self.bar = try container.decode(
4
0
1.5k
Dec ’23
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 How are child processes sandboxed?
Hello, I have a follow up question. It is by design the sandbox gets inherited when running a command line tool using the Process.run() from an application signed by a different Team ID? Eg. the PowerPoint app authored by the Team ID UBF8T346G9 runs a tool signed by Team ID 44X73QA89R (a different developer team) and the tools inherit's the PowerPoint app's sandbox.
Topic: Privacy & Security SubTopic: General Tags:
May ’25
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 Configurations for Private and Public CloudKit
I did manage to save my Entities to CloudKit with SwiftData but the default database is the private database. I need to store some Entities in the private and other Entities in the public CloudKit database. How do I manage that with SwiftData? With CoreData I always used different configurations for both private and public and added the entities to one or the other.
6
0
6.7k
Jun ’23
Syncing SwiftData with server API
Hello, I have a List view that populates from a REST API (listApiKeys() calls out to server). The response is decoded and stored in a swiftdata model. It looks like this: NavigationStack(path: $path) { List { ForEach(keys) { key in NavigationLink(value: key) { Text(key.name) } } } .navigationDestination(for: GtApiKey.self) { key in EditApiKeyView(apiKey: key, navigationPath: $path) } .refreshable { try? modelContext.delete(model: GtApiKey.self) await listApiKeys() } .toolbar { Button(Create Key, systemImage: plus, action: createKey) } } .navigationTitle(test apikeys) .task { await listApiKeys() } This all works fine and SwiftData stores everything great. If I click into a single object's edit view, everything works great as well. My question is how do I sync changes to the SwiftData entry back to the server. My edit view uses a @Bindable and any changes auto-sync to SwiftData (expected). But, I can't seem to figure out where to catch those events or prevent them before I ca
0
0
888
Feb ’24
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 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 Once my core data model is set up, how do I then instantiate objects that follow the hierarchy tree?
First, you'll have a better chance of getting answers if you move this question to the Core Data or Cocoa sections of the forum. The Core Data and Cocoa sections are in the App Frameworks section of the developer forums.To answer your question about what project an ObjectA belongs to, add relationships to your Core Data model. Your Project entity would have a relationship for its ObjectA items. The destination for this relationship is ObjectA. Your ObjectA entity would have a relationship for its project whose destination is Project. Each relationship is the inverse of the other relationship.The relationships for ObjectA and ObjectB are similar. Create a second relationship for ObjectA for its ObjectB items. Create a relationship for the ObjectB entity for the ObjectA it belongs to. These two relationships are the inverses of each other.In code the relationships are just variables. The project relationship for O
Replies
Boosts
Views
Activity
Sep ’17
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
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
Reply to SwiftData @Model does not conform to the 'Sendable' protocol; thi
I've fixed this by creating a struct for the data returned by SwiftData. I stuff the struct with the SwiftData and use the struct in my UICollectionViewDiffableDataSource. I am using SwiftData with UIKit.
Replies
Boosts
Views
Activity
Jul ’24
How do you access SwiftData containers across modules?
I cannot test at the moment, but have not found documentation on this yet. I don't have a sense of how ModelContainer works across targets. I have not, for example, seen a project with SwiftData unit tests yet.
Replies
1
Boosts
0
Views
611
Activity
Jul ’23
SwiftData Unexpected type for CompositeAttribute
I'm getting SwiftData/SchemaProperty.swift:369: Fatal error: Unexpected type for CompositeAttribute CLLocationCoordinate2D in the following situation - this is simplified, but demonstrates the issue. There are a lot of posts discussing Measurements running into the same issue, and the recommended fix is to turn the Measurement (or CLLocationCoordinate2D in this example) into a computed property and generate it on the fly. I'm trying to cache instances of CLLocationCoordinate2D, rather than creating new ones every time a View renders, so those work arounds don't work around. The SwiftData docs seem to indicate that this should be possible. Can anyone recommend a fix? Thanks in advance. import SwiftData import MapKit @Model final class foo : Codable { var bar: SomeStruct init( bar: SomeStruct ) { self.bar = bar } enum CodingKeys : CodingKey { case bar } init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) self.bar = try container.decode(
Replies
4
Boosts
0
Views
1.5k
Activity
Dec ’23
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
Reply to How are child processes sandboxed?
Hello, I have a follow up question. It is by design the sandbox gets inherited when running a command line tool using the Process.run() from an application signed by a different Team ID? Eg. the PowerPoint app authored by the Team ID UBF8T346G9 runs a tool signed by Team ID 44X73QA89R (a different developer team) and the tools inherit's the PowerPoint app's sandbox.
Topic: Privacy & Security SubTopic: General Tags:
Replies
Boosts
Views
Activity
May ’25
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 Configurations for Private and Public CloudKit
I did manage to save my Entities to CloudKit with SwiftData but the default database is the private database. I need to store some Entities in the private and other Entities in the public CloudKit database. How do I manage that with SwiftData? With CoreData I always used different configurations for both private and public and added the entities to one or the other.
Replies
6
Boosts
0
Views
6.7k
Activity
Jun ’23
Syncing SwiftData with server API
Hello, I have a List view that populates from a REST API (listApiKeys() calls out to server). The response is decoded and stored in a swiftdata model. It looks like this: NavigationStack(path: $path) { List { ForEach(keys) { key in NavigationLink(value: key) { Text(key.name) } } } .navigationDestination(for: GtApiKey.self) { key in EditApiKeyView(apiKey: key, navigationPath: $path) } .refreshable { try? modelContext.delete(model: GtApiKey.self) await listApiKeys() } .toolbar { Button(Create Key, systemImage: plus, action: createKey) } } .navigationTitle(test apikeys) .task { await listApiKeys() } This all works fine and SwiftData stores everything great. If I click into a single object's edit view, everything works great as well. My question is how do I sync changes to the SwiftData entry back to the server. My edit view uses a @Bindable and any changes auto-sync to SwiftData (expected). But, I can't seem to figure out where to catch those events or prevent them before I ca
Replies
0
Boosts
0
Views
888
Activity
Feb ’24