Search results for

“SwiftData inheritance relationship”

4,982 results found

Post

Replies

Boosts

Views

Activity

Xcode 15 has problem of generated Swift NSObject headers: Property type 'NSInteger' (aka 'long') is incompatible with type 'NSUInteger' (aka 'unsigned long') inherited from 'NSObject'
The generated Obj-C header for Swift is called @property (nonatomic, readonly) NSInteger hash; However, it caused a compiler error: Property type 'NSInteger' (aka 'long') is incompatible with type 'NSUInteger' (aka 'unsigned long') inherited from 'NSObject' Version 15.0 beta (15A5160n)
7
0
1.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
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 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
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
Xcode 15 has problem of generated Swift NSObject headers: Property type 'NSInteger' (aka 'long') is incompatible with type 'NSUInteger' (aka 'unsigned long') inherited from 'NSObject'
The generated Obj-C header for Swift is called @property (nonatomic, readonly) NSInteger hash; However, it caused a compiler error: Property type 'NSInteger' (aka 'long') is incompatible with type 'NSUInteger' (aka 'unsigned long') inherited from 'NSObject' Version 15.0 beta (15A5160n)
Replies
7
Boosts
0
Views
1.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
SwiftData lazy loaded list
Are SwiftData queries lazy loaded when used in conjunction with SwiftUI List? @Query var posts: [PostModel] List { ForEach(posts, id: .id) { post in PostView(post) } } If the code above is not lazy loaded, how can we make it lazy loaded?
Replies
3
Boosts
0
Views
636
Activity
Nov ’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 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
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
Finding source for SwiftData array behaviour
Hello Apple Developer Forum, I got the following statement from the AI model. It seems it is also reflecting my real-world experience. Where do I find an official source that fully describes the array on swiftData model behaviour? When a SwiftData model contains an array of value types, such as [String] or [Int], the array's order is preserved
Replies
4
Boosts
0
Views
285
Activity
Oct ’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
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
Reply to Xcode 12.0.1 "No such module"
Just resolved it on Xcode 13.1 My PodFile had to be like below in order to get it working. workspace '' platform :ios, '15.1' target '' do use_frameworks! pod 'AppAuth' target 'Tests' do inherit! :search_paths end target 'UITests' do #inherit :search_paths end end```
Replies
Boosts
Views
Activity
Nov ’21