Search results for

“SwiftData inheritance relationship”

4,982 results found

Post

Replies

Boosts

Views

Activity

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
Can a private database entity have a relationship to a public database entity?
I’m using NSPersistentCloudKitContainer and I’m utilising the public database and also the user’s private database. For example I have an entity called Category which has a many-to-many relationship to an entity called NewsArticle. So the NewsArticles exist in the public database for the user to browse, but he can add them to a category which will live in his private database. So that’s my question, is it possible for an entity which exists a in the private database to have a relationship to another entity in a public database?
1
0
977
May ’23
SwiftData Models and SortDesc. Only Work in One Swift File
Hey everyone, I found a possible SwiftData Release-only issue with nested sort descriptors on an optional relationship. In a minimal repro, sorting a @Query by a nested optional relationship key path like: SortDescriptor(InvestigationPhotoAsset.imageAnalysis?.overallAestheticsScore, order: .reverse) works in Debug, but crashes at runtime in Release. The surprising part is that the crash depends on file layout: if the active SwiftData models and the sort logic are kept in the same Swift file, the app works if the same models are split into separate files, the Release build crashes, 'Debug' will also work The repro was reduced to just two SwiftData models: InvestigationPhotoAsset InvestigationImageAnalysis So this looks less like an app-modeling issue and more like a SwiftData/compiler/codegen issue related to nested sort metadata in optimized builds. If useful, I can also give you a slightly more formal version with a title and code snippet block. Please ch
4
0
271
3w
SwiftData delete doesn't work
I'm using SwiftData to save title and images. When I delete the model, the fetched model count reduces. But in the settings - storage - myApp, the document and data does not change. I deleted all the models but its like 9GB left. I followed the SwiftData example app provided by Apple as much as possible. I tried isAutosaveEnabled = false and put save() to every delete functions. deleteRule = .cascade
0
0
615
Mar ’24
ForEach and SwiftData Model
Hello World ! I have an issue with a ForEach loop and a SwiftData Model Here is the code : import Foundation import SwiftData @Model final class Todo { var id: UUID var content: String var isDone: Bool var isImportant: Bool var sortValue: Int init(content: String, isDone: Bool, isImportant: Bool) { self.id = UUID() self.content = content self.isDone = isDone self.isImportant = isImportant if isImportant{ self.sortValue = 0 } else { self.sortValue = 1 } } } final class Tag { var id: UUID var content: String init(content: String) { self.id = UUID() self.content = content } } and the content view : import SwiftUI import SwiftData struct AddTodoView: View { @Environment(.modelContext) private var modelContext @Environment(.dismiss) var dismiss @Query private var tags: [Tag] @State private var selectedTag: UUID @State private var content: String = @State private var isImportant: Bool = false @State private var showAlert: Bool = false @State private var showAchivement: Bool = false var b
1
0
1.4k
Nov ’23
SwiftData ModelContext.insert crashes, why?
This simple test fails in my project. Similar code in my application also crashes. How do I debug the problem? What project settings are required. I have added SwiftData as a framework to test (and application) targets? Thanks, The problem is with: modelContext.insert(item) Thread 1: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0) import XCTest import SwiftData @Model class FakeModel { var name: String init(name: String) { self.name = name } } @MainActor final class FakeModelTests: XCTestCase { var modelContext: ModelContext! override func setUp() { super.setUp() do { let container = try ModelContainer(for: FakeModel.self, configurations: ModelConfiguration(isStoredInMemoryOnly: true)) modelContext = container.mainContext } catch { XCTFail(Failed to create ModelContainer: (error)) modelContext = nil } } func testSaveFetchDeleteFakeItem() { guard let modelContext = modelContext else { XCTFail(ModelContext must be initialized) return } let item = FakeModel(name: Test) modelContext.inser
4
0
267
Aug ’25
Reply to SwiftData SortDescriptor Limitation...
Could be the same issue. I tried reporting this directly to Apple with a request for Technical Assistance because I hadn't seen any other reports of this behavior. I had developed a SwiftData app that used CloudKit and therefore required all model relationships to be treated as optional. I was sorting an object using a relationship's title field (which was clearly optional) and this worked fine in all simulator and Xcode downloads with no issues. I didn't run into it until I tried using TestFlight to get some beta feedback and the app immediately crashed and the feedback was sparse so I took several months to finally track down what was causing it. I would certainly like to see this fixed because it creates limitations that only surface very late ih the app dev process which is very frustrating. If it shouldn't ever work then it should also crash in the simulator and any Xcode downloads IMHO.
Aug ’25
SwiftData CloudKit sync broken on iOS 26
Hi everyone, I’m running into a breaking issue with SwiftData automatic CloudKit syncing on iOS 26, and I'm trying to determine if this is a known regression or a new configuration requirement I missed. The Setup: My setup is extremely standard; I am using the default configuration exactly as described in Apple's documentation here: https://developer.apple.com/documentation/swiftdata/syncing-model-data-across-a-persons-devices The schema is very simple: A single @Model class. No relationships. The Issue: Prior to iOS 26, this exact app was successfully syncing data between devices and to iCloud without issues. Immediately after the iOS 26 update, syncing stopped completely. I haven't changed any code, but when I check the CloudKit Console, I am seeing some BAD_REQUEST errors during sync attempts. Since I am using the default SwiftData sync (and not manual CKRecord handling), I’m not sure how my client code could be triggering a bad request unless the schema requirements hav
1
0
295
Jan ’26
SwiftData Upsert
How do I get Upsert to work in SwiftData? I have a model: @Model class Address: Identifiable { @Attribute(.unique) var id: Int = 0 var number: String = var street: String? var city: String? } When I insert a duplicate record with the same data attributes (specifically overlapping id) and execute modelContext.save() I receive a EXC_BREAKPOINT. let addressA = Address(id: 1, number: 2300, street: E Main St, city: Small Town ); modelContext.insert(addressA) try? modelContext.save() let addressAv2 = Address(id: 1, number: 2300, street: E Main St, city: Small Town ); modelContext.insert(addressAv2) try? modelContext.save() // This fails Is there a better way to handle updates?
1
0
953
Nov ’23
Migrating a swiftData project to CloudKit to implement iCloudSync.
My project is using swiftData and I want to implement iCloud sync in it. Now, my data base doesnt have any optional attributes or relationships and CloudKit wants them to be optional. So, rather than editing all code with unwrapping code for the optionals, how can I provide a bridge that does so in the last stage of actually saving to the store? Sort of, capture it in a proxy object before writing and after reading from the store. Is there a neat way that can save a lot of debugging? I have code snippets from chat gpt and they are hard to debug. This is my first project in swiftUI. Thanks. Neerav
3
0
190
May ’25
Reply to Unable to initialized a class that subclasses SKShapeNode, specifically (rectOf: CGSize)
First of all, you should better read this section of the Swift Book. Class Inheritance and Initialization - https://docs.swift.org/swift-book/LanguageGuide/Initialization.html#ID216 Some points in your case: In SKShapeNode, init(rectOf:) is a convenience initializer To call a convenience initializer in your own initializer, the convenience initializer needs to be inherited and your own initializer needs to be another convenience initializer To inherit convenience initializers, you need to [1] inherit all the designated initializers or [2] define (override) all the designated initializers ... (You should better read all other parts of the section carefully.) Thus, conclusion. class PegBase : SKShapeNode { tt tt//To use `init(rectOf:)`, your own init needs to be a convenience initializer ttconvenience init(rectOfPegBase size: CGSize) { tttt//Call `self.init(rectOf:)`, which needs to be inherited from super class ttttself.init(rectOf: size) ttttself.fillColor = SKColo
Topic: Programming Languages SubTopic: Swift Tags:
Jul ’20
Reply to SwiftData relationships
In the “Vegetable” class, why is the field “notes” an array of type Notes? You may have several notes, so it is logical to get them in an array. What else did you think about ? Again in the “Vegetable” class does the field “notes” get stored in the database, if so what is stored? By default, all non-computed attributes are stored. Unless you use the @Transient macro. In the “Note” Class it looks like the whole of the class “Vegetable” gets stored in the variable “vegetable”, which may or may not get stored in the database. With @Relationship, SwiftData knows what needs to be saved to be able to rebuild the relations when needed. This tutorial should give you some insight.
May ’24
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
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
Can a private database entity have a relationship to a public database entity?
I’m using NSPersistentCloudKitContainer and I’m utilising the public database and also the user’s private database. For example I have an entity called Category which has a many-to-many relationship to an entity called NewsArticle. So the NewsArticles exist in the public database for the user to browse, but he can add them to a category which will live in his private database. So that’s my question, is it possible for an entity which exists a in the private database to have a relationship to another entity in a public database?
Replies
1
Boosts
0
Views
977
Activity
May ’23
SwiftData Models and SortDesc. Only Work in One Swift File
Hey everyone, I found a possible SwiftData Release-only issue with nested sort descriptors on an optional relationship. In a minimal repro, sorting a @Query by a nested optional relationship key path like: SortDescriptor(InvestigationPhotoAsset.imageAnalysis?.overallAestheticsScore, order: .reverse) works in Debug, but crashes at runtime in Release. The surprising part is that the crash depends on file layout: if the active SwiftData models and the sort logic are kept in the same Swift file, the app works if the same models are split into separate files, the Release build crashes, 'Debug' will also work The repro was reduced to just two SwiftData models: InvestigationPhotoAsset InvestigationImageAnalysis So this looks less like an app-modeling issue and more like a SwiftData/compiler/codegen issue related to nested sort metadata in optimized builds. If useful, I can also give you a slightly more formal version with a title and code snippet block. Please ch
Replies
4
Boosts
0
Views
271
Activity
3w
SwiftData delete doesn't work
I'm using SwiftData to save title and images. When I delete the model, the fetched model count reduces. But in the settings - storage - myApp, the document and data does not change. I deleted all the models but its like 9GB left. I followed the SwiftData example app provided by Apple as much as possible. I tried isAutosaveEnabled = false and put save() to every delete functions. deleteRule = .cascade
Replies
0
Boosts
0
Views
615
Activity
Mar ’24
ForEach and SwiftData Model
Hello World ! I have an issue with a ForEach loop and a SwiftData Model Here is the code : import Foundation import SwiftData @Model final class Todo { var id: UUID var content: String var isDone: Bool var isImportant: Bool var sortValue: Int init(content: String, isDone: Bool, isImportant: Bool) { self.id = UUID() self.content = content self.isDone = isDone self.isImportant = isImportant if isImportant{ self.sortValue = 0 } else { self.sortValue = 1 } } } final class Tag { var id: UUID var content: String init(content: String) { self.id = UUID() self.content = content } } and the content view : import SwiftUI import SwiftData struct AddTodoView: View { @Environment(.modelContext) private var modelContext @Environment(.dismiss) var dismiss @Query private var tags: [Tag] @State private var selectedTag: UUID @State private var content: String = @State private var isImportant: Bool = false @State private var showAlert: Bool = false @State private var showAchivement: Bool = false var b
Replies
1
Boosts
0
Views
1.4k
Activity
Nov ’23
SwiftData ModelContext.insert crashes, why?
This simple test fails in my project. Similar code in my application also crashes. How do I debug the problem? What project settings are required. I have added SwiftData as a framework to test (and application) targets? Thanks, The problem is with: modelContext.insert(item) Thread 1: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0) import XCTest import SwiftData @Model class FakeModel { var name: String init(name: String) { self.name = name } } @MainActor final class FakeModelTests: XCTestCase { var modelContext: ModelContext! override func setUp() { super.setUp() do { let container = try ModelContainer(for: FakeModel.self, configurations: ModelConfiguration(isStoredInMemoryOnly: true)) modelContext = container.mainContext } catch { XCTFail(Failed to create ModelContainer: (error)) modelContext = nil } } func testSaveFetchDeleteFakeItem() { guard let modelContext = modelContext else { XCTFail(ModelContext must be initialized) return } let item = FakeModel(name: Test) modelContext.inser
Replies
4
Boosts
0
Views
267
Activity
Aug ’25
Reply to SwiftData SortDescriptor Limitation...
Could be the same issue. I tried reporting this directly to Apple with a request for Technical Assistance because I hadn't seen any other reports of this behavior. I had developed a SwiftData app that used CloudKit and therefore required all model relationships to be treated as optional. I was sorting an object using a relationship's title field (which was clearly optional) and this worked fine in all simulator and Xcode downloads with no issues. I didn't run into it until I tried using TestFlight to get some beta feedback and the app immediately crashed and the feedback was sparse so I took several months to finally track down what was causing it. I would certainly like to see this fixed because it creates limitations that only surface very late ih the app dev process which is very frustrating. If it shouldn't ever work then it should also crash in the simulator and any Xcode downloads IMHO.
Replies
Boosts
Views
Activity
Aug ’25
SwiftData CloudKit sync broken on iOS 26
Hi everyone, I’m running into a breaking issue with SwiftData automatic CloudKit syncing on iOS 26, and I'm trying to determine if this is a known regression or a new configuration requirement I missed. The Setup: My setup is extremely standard; I am using the default configuration exactly as described in Apple's documentation here: https://developer.apple.com/documentation/swiftdata/syncing-model-data-across-a-persons-devices The schema is very simple: A single @Model class. No relationships. The Issue: Prior to iOS 26, this exact app was successfully syncing data between devices and to iCloud without issues. Immediately after the iOS 26 update, syncing stopped completely. I haven't changed any code, but when I check the CloudKit Console, I am seeing some BAD_REQUEST errors during sync attempts. Since I am using the default SwiftData sync (and not manual CKRecord handling), I’m not sure how my client code could be triggering a bad request unless the schema requirements hav
Replies
1
Boosts
0
Views
295
Activity
Jan ’26
SwiftData Upsert
How do I get Upsert to work in SwiftData? I have a model: @Model class Address: Identifiable { @Attribute(.unique) var id: Int = 0 var number: String = var street: String? var city: String? } When I insert a duplicate record with the same data attributes (specifically overlapping id) and execute modelContext.save() I receive a EXC_BREAKPOINT. let addressA = Address(id: 1, number: 2300, street: E Main St, city: Small Town ); modelContext.insert(addressA) try? modelContext.save() let addressAv2 = Address(id: 1, number: 2300, street: E Main St, city: Small Town ); modelContext.insert(addressAv2) try? modelContext.save() // This fails Is there a better way to handle updates?
Replies
1
Boosts
0
Views
953
Activity
Nov ’23
Migrating a swiftData project to CloudKit to implement iCloudSync.
My project is using swiftData and I want to implement iCloud sync in it. Now, my data base doesnt have any optional attributes or relationships and CloudKit wants them to be optional. So, rather than editing all code with unwrapping code for the optionals, how can I provide a bridge that does so in the last stage of actually saving to the store? Sort of, capture it in a proxy object before writing and after reading from the store. Is there a neat way that can save a lot of debugging? I have code snippets from chat gpt and they are hard to debug. This is my first project in swiftUI. Thanks. Neerav
Replies
3
Boosts
0
Views
190
Activity
May ’25
SwiftData Data Deleting Unwantedly
Hi, I have two SwiftData models that are not working as intended. I'm able to add data to the models, but sometimes after refreshing the app data is missing. Any guidance would be greatly appreciated.
Topic: Design SubTopic: General Tags:
Replies
2
Boosts
0
Views
1.1k
Activity
Oct ’24
What should I do if I want to mimic real-world occlusion relationships
I have a problem. In AR mode, objects or people in the real environment cannot dynamically block the virtual 3D model. What should I do if I want to mimic real-world occlusion relationships?
Replies
1
Boosts
0
Views
336
Activity
Nov ’24
Reply to Unable to initialized a class that subclasses SKShapeNode, specifically (rectOf: CGSize)
First of all, you should better read this section of the Swift Book. Class Inheritance and Initialization - https://docs.swift.org/swift-book/LanguageGuide/Initialization.html#ID216 Some points in your case: In SKShapeNode, init(rectOf:) is a convenience initializer To call a convenience initializer in your own initializer, the convenience initializer needs to be inherited and your own initializer needs to be another convenience initializer To inherit convenience initializers, you need to [1] inherit all the designated initializers or [2] define (override) all the designated initializers ... (You should better read all other parts of the section carefully.) Thus, conclusion. class PegBase : SKShapeNode { tt tt//To use `init(rectOf:)`, your own init needs to be a convenience initializer ttconvenience init(rectOfPegBase size: CGSize) { tttt//Call `self.init(rectOf:)`, which needs to be inherited from super class ttttself.init(rectOf: size) ttttself.fillColor = SKColo
Topic: Programming Languages SubTopic: Swift Tags:
Replies
Boosts
Views
Activity
Jul ’20
Reply to SwiftData relationships
In the “Vegetable” class, why is the field “notes” an array of type Notes? You may have several notes, so it is logical to get them in an array. What else did you think about ? Again in the “Vegetable” class does the field “notes” get stored in the database, if so what is stored? By default, all non-computed attributes are stored. Unless you use the @Transient macro. In the “Note” Class it looks like the whole of the class “Vegetable” gets stored in the variable “vegetable”, which may or may not get stored in the database. With @Relationship, SwiftData knows what needs to be saved to be able to rebuild the relations when needed. This tutorial should give you some insight.
Replies
Boosts
Views
Activity
May ’24
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