Search results for

“SwiftData inheritance relationship”

4,982 results found

Post

Replies

Boosts

Views

Activity

Reply to SwiftData Predicates crashes when using Generic
Ran into this as well. The compiler is optimizing something incorrectly for release builds. Using Predicate init directly (instead of the Macro) doesn't resolve the issue. Nor does any combo of explicit/verbose casting. Something as simple as this: func fetchModel(with id: UUID, prefetching relationshipKeyPaths: [PartialKeyPath] = []) throws -> M where M: PersistentModel, M.ID == UUID { var fetchDescriptor = FetchDescriptor() fetchDescriptor.relationshipKeyPathsForPrefetching = relationshipKeyPaths fetchDescriptor.predicate = #Predicate { $0.id == id } fetchDescriptor.fetchLimit = 1 guard let model: M = try? modelContext.fetch(fetchDescriptor).first else { throw SwiftDataRepoError.modelNotFound(withId: id) } return model } Results in this crash: SwiftData/DataUtilities.swift:85: Fatal error: Couldn't find Person. on Person with fields [SwiftData.Schema.PropertyMetadata(name: id, keypath: Person., defaultValue: Optional(5CAE942A-EF4E-4B89-A777-D79153C7F276), metadata: nil) .... Only thing that work
Apr ’25
SwiftData Predicates crashes when using Generic
I have been dealing with an error for almost 2 days now that caused my programme to crash on runtime with Thread 10: EXC_BAD_ACCESS (code=1, address=0x0) error , only when using Release mode. After many trial and errors and narrowing down the root problem I became suspicious to #Predicate and Generics being the root cause of the problem so I made these views to test it out. import SwiftUI import SwiftData struct DataBaseTestGeneric: View { @State private var models: [Model] = [] var body: some View { viewLoader{ let reporter = Reporter() let pred = #Predicate{ model in return true } models = await reporter.fetch(pred) }content: { List{ ForEach(models){ model in Text((model.id)) } } } } } and a non-Generic version : import SwiftData struct DatabaseTest: View { @State private var transactions: [Transaction] = [] var body: some View { viewLoader { let reporter = Reporter() let pred = #Predicate{ dec in return true } let decs = await reporter.fetch(pred) transactions = decs }content:{ List{ ForE
3
0
652
Dec ’24
SwiftData JSONDataStore with relationships
I am trying to add a custom JSON DataStore and DataStoreConfiguration for SwiftData. Apple kindly provided some sample code in the WWDC24 session, Create a custom data store with SwiftData, and (once updated for API changes since WWDC) that works fine. However, when I try to add a relationship between two classes, it fails. Has anyone successfully made a JSONDataStore with a relationship? Here's my code; firstly the cleaned up code from the WWDC session: import SwiftData final class JSONStoreConfiguration: DataStoreConfiguration { typealias Store = JSONStore var name: String var schema: Schema? var fileURL: URL init(name: String, schema: Schema? = nil, fileURL: URL) { self.name = name self.schema = schema self.fileURL = fileURL } static func == (lhs: JSONStoreConfiguration, rhs: JSONStoreConfiguration) -> Bool { return lhs.name == rhs.name } func hash(into hasher: inout Hasher) { hasher.combine(name) } } final class JSONStore: DataStore { typealias Configuration
2
0
770
Apr ’25
SwiftData "Auto Inserts" array into ModelContext
Definitely one of the stranger quirks of SwiftData I've come across. I have a ScriptView that shows Line entities related to a Production, and a TextEnterScriptView that’s presented in a sheet to input text. I’m noticing that every time I type in the TextEditor within TextEnterScriptView, a new Line shows up in ScriptView — even though I haven’t explicitly inserted it into the modelContext. I'm quite confused because even though I’m only assigning a new Line to a local @State array in TextEnterScriptView, every keystroke in the TextEditor causes a duplicate Line to appear in ScriptView. In other words, Why is SwiftData creating new Line entities every time I type in the TextEditor, even though I’m only assigning to a local @State array and not explicitly inserting them into the modelContext? Here is my minimal reproducible example: import SwiftData import SwiftUI @main struct testApp: App { var body: some Scene { WindowGroup { ContentView() .modelContainer(for: Line.self, isAutosave
1
0
93
Apr ’25
SwiftData serious bug with relationships and CloudKit in iOS 18.0 (Xcode 16 Beta)
Hi guys. Can someone please confirm this bug so I report it? The issue is that SwiftData relationships don't update the views in some specific situations on devices running iOS 18 Beta. One clear example is with CloudKit. I created a small example for testing. The following code creates two @models, one to store bands and another to store their records. The following code works with no issues. (You need to connect to a CloudKit container and test it on two devices) import SwiftUI import SwiftData struct ContentView: View { @Environment(.modelContext) private var modelContext @Query private var records: [Record] var body: some View { NavigationStack { List(records) { record in VStack(alignment: .leading) { Text(record.title) Text(record.band?.name ?? Undefined) } } .toolbar { ToolbarItem { Button(Add Record) { let randomNumber = Int.random(in: 1...100) let newBand = Band(name: New Band (randomNumber), records: nil) modelContext.insert(newBand) let newRecord = Record(title: New Record
3
0
888
Apr ’25
Can @Query and ModelActor co-exist? How?
Context: The SwiftUI @Query macro has an internal modelContext. The ModelActor also has a modelContext, from which the data should be read/written. Issue: When writing to @Model data fetched with @Query macro using a ModelActor, it will crash in the most not-obvious ways. Also, fetching @Model with ModelActor will result in errors in Swift 6 since @Model aren't sendable. Problem to Solve: - How to write a good amount of data to SwiftData/CoreData without blocking the UI thread? Would the recommendation from the Apple team be that a large amount of data should be read/written with ModelActor and a small amount should be done with the @Query's internal modelContext ?
1
0
158
Apr ’25
When to use structs with swift data?
I am unsure the correct way to model my data. I have a swift data object and then some referenced objects. Is there ever a reason those should just be structs or should they always be swift data objects themselves? for example right now this is what I'm doing: @Model final class Exam { var timestamp: Date @Attribute(.unique) var examID: UUID var title: String var questions: [Question] ... } and Question is struct Question: Codable, Identifiable { var id: UUID var number: Int var points: Int var prompt: String var answer: String } is there any problem with this or should I not be using a Struct for Question and instead use another Swift Data object with @Relationship ? I thought since its a simple object just using a struct would be fine, however... when I create a new Question object, it seems to create SwiftUI retain cycles with the warning === AttributeGraph: cycle detected through attribute 633984 === in the terminal for example, Button(Add Question, systemImage: questionmark.diamond) { let newQue
3
0
1.3k
Sep ’24
ModifyPromo 409: State Error
When calling modifypromo, I keep getting this error: error: HTTP status code 409, body { errors : [ { id : 7aeb5c20-576d-4500-ad65-525d298d2093, status : 409, code : STATE_ERROR, title : The request cannot be fulfilled because of the state of another resource., detail : Cannot invoke com.apple.its.pricing.api.model.Country.countryCodeISO2A() because the return value of com.apple.its.pricing.api.model.offers.AdHocOfferProduct.country() is null } ] } My request is: Where id is the encrypted values needed { data: { attributes: {}, relationships: { prices: { data: [ { id: id, type: subscriptionPromotionalOfferPrices } ] } }, type: subscriptionPromotionalOffers, id: id }, included: [ { attributes: {}, id: subscriptionPromotionalOfferPrices, relationships: { subscriptionPricePoint: { data: { id: id, type: subscriptionPricePoints } }, territory: { data: { id: USA, type: territories } } } } ] }
2
0
126
Apr ’25
Reply to Strange media player overlay main screen
Resolved. In the app, all UI elements was created manually and all ViewController inherited from a BaseViewController, including MainMenuViewController. a. the code caused the issue: @interface BaseViewController: AVPlayerViewController b. modified code: @interface BaseViewController: UIViewController Why the base ViewController inherited from AVPlayerViewController, because there's a VideoViewController that will be used to play video. unfortunately, OC don't support multiple inheritance, so I have to embed the base ViewController's functions into VideoViewController instead of inheritance. It's an issue caused by not being careful enough when modifying code.
Topic: UI Frameworks SubTopic: UIKit
Apr ’25
Reply to App Store Connect analytics reports return 500 API error
Now I started facing another problem with pagination: next url is invalid. Get: https://api.appstoreconnect.apple.com/v1/analyticsReportRequests/{id}/relationships/reports?cursor=Mg Error: { errors: [ { id: 56e0cfab-4e86-4e4b-9a12-d76277ad9f94, status: 400, code: PARAMETER_ERROR.INVALID, title: A parameter has an invalid value, detail: 'Mg' is not a valid cursor for this request, source: { parameter: cursor } } ] }
Apr ’25
SwiftData Many-To-Many Relationship: Failed to fulfill link PendingRelationshipLink
Hi there, I got two models here: Two Models, with Many-To-Many Relationship @Model final class PresetParams: Identifiable { @Attribute(.unique) var id: UUID = UUID() var positionX: Float = 0.0 var positionY: Float = 0.0 var positionZ: Float = 0.0 var volume: Float = 1.0 @Relationship(deleteRule: .nullify, inverse: Preset.presetAudioParams) var preset = [Preset]() init(position: SIMD3, volume: Float) { self.positionX = position.x self.positionY = position.y self.positionZ = position.z self.volume = volume self.preset = [] } var position: SIMD3 { get { return SIMD3(x: positionX, y: positionY, z: positionZ) } set { positionX = newValue.x positionY = newValue.y positionZ = newValue.z } } } @Model final class Preset: Identifiable { @Attribute(.unique) var id: UUID = UUID() var presetName: String var presetDesc: String? var presetAudioParams = [PresetParams]() // Many-To-Many Relationship. init(presetName: String, presetDesc: String? = nil) { self.presetName = presetName self.presetDesc =
1
0
160
Apr ’25
error: the replacement path doesn't exist <- how bad is this error, should i care - is it important?
I get this error, i have my own DIKit, and i want to use swiftdata for showing info from persisten model. It works all over the app, but i get this error with my .sheet. // JobCreationView.swift // Features // // Created by Jens Vik on 26/03/2025. // import SwiftUI import DesignKit import DIKit import PresentationKit import CoreKit import DomainKit import SwiftData public struct JobCreationView: View { @Binding var isPresented: Bool // Inject view model using DIKit's property wrapper @Injected((any JobCreationViewModelProtocol).self) private var viewModel // Form state @Injected(ModelContext.self) private var modelContext @State private var date = Date() @State private var isASAP = false @State private var price = @State private var jobType = Fiks @State private var description = // Available job types private let jobTypes = [Fiks, Fiksit] @Query private var userContexts: [UserContextModel] public init(isPresented: Binding) { self._isPresented = isPresented print(DEBUG: JobCreationView ini
1
0
124
Apr ’25
Swift Data initiate
I am working with SwiftData and get the below error. I can't find any documentation on it to see what to fix. Any help would be appreciated. Fatal error: This relationship already has a value but it's not the target:
Replies
1
Boosts
0
Views
109
Activity
Apr ’25
Reply to SwiftData Predicates crashes when using Generic
Ran into this as well. The compiler is optimizing something incorrectly for release builds. Using Predicate init directly (instead of the Macro) doesn't resolve the issue. Nor does any combo of explicit/verbose casting. Something as simple as this: func fetchModel(with id: UUID, prefetching relationshipKeyPaths: [PartialKeyPath] = []) throws -> M where M: PersistentModel, M.ID == UUID { var fetchDescriptor = FetchDescriptor() fetchDescriptor.relationshipKeyPathsForPrefetching = relationshipKeyPaths fetchDescriptor.predicate = #Predicate { $0.id == id } fetchDescriptor.fetchLimit = 1 guard let model: M = try? modelContext.fetch(fetchDescriptor).first else { throw SwiftDataRepoError.modelNotFound(withId: id) } return model } Results in this crash: SwiftData/DataUtilities.swift:85: Fatal error: Couldn't find Person. on Person with fields [SwiftData.Schema.PropertyMetadata(name: id, keypath: Person., defaultValue: Optional(5CAE942A-EF4E-4B89-A777-D79153C7F276), metadata: nil) .... Only thing that work
Replies
Boosts
Views
Activity
Apr ’25
SwiftData Predicates crashes when using Generic
I have been dealing with an error for almost 2 days now that caused my programme to crash on runtime with Thread 10: EXC_BAD_ACCESS (code=1, address=0x0) error , only when using Release mode. After many trial and errors and narrowing down the root problem I became suspicious to #Predicate and Generics being the root cause of the problem so I made these views to test it out. import SwiftUI import SwiftData struct DataBaseTestGeneric: View { @State private var models: [Model] = [] var body: some View { viewLoader{ let reporter = Reporter() let pred = #Predicate{ model in return true } models = await reporter.fetch(pred) }content: { List{ ForEach(models){ model in Text((model.id)) } } } } } and a non-Generic version : import SwiftData struct DatabaseTest: View { @State private var transactions: [Transaction] = [] var body: some View { viewLoader { let reporter = Reporter() let pred = #Predicate{ dec in return true } let decs = await reporter.fetch(pred) transactions = decs }content:{ List{ ForE
Replies
3
Boosts
0
Views
652
Activity
Dec ’24
SwiftData JSONDataStore with relationships
I am trying to add a custom JSON DataStore and DataStoreConfiguration for SwiftData. Apple kindly provided some sample code in the WWDC24 session, Create a custom data store with SwiftData, and (once updated for API changes since WWDC) that works fine. However, when I try to add a relationship between two classes, it fails. Has anyone successfully made a JSONDataStore with a relationship? Here's my code; firstly the cleaned up code from the WWDC session: import SwiftData final class JSONStoreConfiguration: DataStoreConfiguration { typealias Store = JSONStore var name: String var schema: Schema? var fileURL: URL init(name: String, schema: Schema? = nil, fileURL: URL) { self.name = name self.schema = schema self.fileURL = fileURL } static func == (lhs: JSONStoreConfiguration, rhs: JSONStoreConfiguration) -> Bool { return lhs.name == rhs.name } func hash(into hasher: inout Hasher) { hasher.combine(name) } } final class JSONStore: DataStore { typealias Configuration
Replies
2
Boosts
0
Views
770
Activity
Apr ’25
Reply to SwiftData "Auto Inserts" array into ModelContext
SwiftData does it automatically for you and it must do it or the autosave functionality wouldn't work. If you would only save one side of a relationship then when the app is restarted the other side would be nil or it crashes if the property is non-optional.
Replies
Boosts
Views
Activity
Apr ’25
SwiftData "Auto Inserts" array into ModelContext
Definitely one of the stranger quirks of SwiftData I've come across. I have a ScriptView that shows Line entities related to a Production, and a TextEnterScriptView that’s presented in a sheet to input text. I’m noticing that every time I type in the TextEditor within TextEnterScriptView, a new Line shows up in ScriptView — even though I haven’t explicitly inserted it into the modelContext. I'm quite confused because even though I’m only assigning a new Line to a local @State array in TextEnterScriptView, every keystroke in the TextEditor causes a duplicate Line to appear in ScriptView. In other words, Why is SwiftData creating new Line entities every time I type in the TextEditor, even though I’m only assigning to a local @State array and not explicitly inserting them into the modelContext? Here is my minimal reproducible example: import SwiftData import SwiftUI @main struct testApp: App { var body: some Scene { WindowGroup { ContentView() .modelContainer(for: Line.self, isAutosave
Replies
1
Boosts
0
Views
93
Activity
Apr ’25
SwiftData serious bug with relationships and CloudKit in iOS 18.0 (Xcode 16 Beta)
Hi guys. Can someone please confirm this bug so I report it? The issue is that SwiftData relationships don't update the views in some specific situations on devices running iOS 18 Beta. One clear example is with CloudKit. I created a small example for testing. The following code creates two @models, one to store bands and another to store their records. The following code works with no issues. (You need to connect to a CloudKit container and test it on two devices) import SwiftUI import SwiftData struct ContentView: View { @Environment(.modelContext) private var modelContext @Query private var records: [Record] var body: some View { NavigationStack { List(records) { record in VStack(alignment: .leading) { Text(record.title) Text(record.band?.name ?? Undefined) } } .toolbar { ToolbarItem { Button(Add Record) { let randomNumber = Int.random(in: 1...100) let newBand = Band(name: New Band (randomNumber), records: nil) modelContext.insert(newBand) let newRecord = Record(title: New Record
Replies
3
Boosts
0
Views
888
Activity
Apr ’25
Can @Query and ModelActor co-exist? How?
Context: The SwiftUI @Query macro has an internal modelContext. The ModelActor also has a modelContext, from which the data should be read/written. Issue: When writing to @Model data fetched with @Query macro using a ModelActor, it will crash in the most not-obvious ways. Also, fetching @Model with ModelActor will result in errors in Swift 6 since @Model aren't sendable. Problem to Solve: - How to write a good amount of data to SwiftData/CoreData without blocking the UI thread? Would the recommendation from the Apple team be that a large amount of data should be read/written with ModelActor and a small amount should be done with the @Query's internal modelContext ?
Replies
1
Boosts
0
Views
158
Activity
Apr ’25
When to use structs with swift data?
I am unsure the correct way to model my data. I have a swift data object and then some referenced objects. Is there ever a reason those should just be structs or should they always be swift data objects themselves? for example right now this is what I'm doing: @Model final class Exam { var timestamp: Date @Attribute(.unique) var examID: UUID var title: String var questions: [Question] ... } and Question is struct Question: Codable, Identifiable { var id: UUID var number: Int var points: Int var prompt: String var answer: String } is there any problem with this or should I not be using a Struct for Question and instead use another Swift Data object with @Relationship ? I thought since its a simple object just using a struct would be fine, however... when I create a new Question object, it seems to create SwiftUI retain cycles with the warning === AttributeGraph: cycle detected through attribute 633984 === in the terminal for example, Button(Add Question, systemImage: questionmark.diamond) { let newQue
Replies
3
Boosts
0
Views
1.3k
Activity
Sep ’24
ModifyPromo 409: State Error
When calling modifypromo, I keep getting this error: error: HTTP status code 409, body { errors : [ { id : 7aeb5c20-576d-4500-ad65-525d298d2093, status : 409, code : STATE_ERROR, title : The request cannot be fulfilled because of the state of another resource., detail : Cannot invoke com.apple.its.pricing.api.model.Country.countryCodeISO2A() because the return value of com.apple.its.pricing.api.model.offers.AdHocOfferProduct.country() is null } ] } My request is: Where id is the encrypted values needed { data: { attributes: {}, relationships: { prices: { data: [ { id: id, type: subscriptionPromotionalOfferPrices } ] } }, type: subscriptionPromotionalOffers, id: id }, included: [ { attributes: {}, id: subscriptionPromotionalOfferPrices, relationships: { subscriptionPricePoint: { data: { id: id, type: subscriptionPricePoints } }, territory: { data: { id: USA, type: territories } } } } ] }
Replies
2
Boosts
0
Views
126
Activity
Apr ’25
Reply to Strange media player overlay main screen
Resolved. In the app, all UI elements was created manually and all ViewController inherited from a BaseViewController, including MainMenuViewController. a. the code caused the issue: @interface BaseViewController: AVPlayerViewController b. modified code: @interface BaseViewController: UIViewController Why the base ViewController inherited from AVPlayerViewController, because there's a VideoViewController that will be used to play video. unfortunately, OC don't support multiple inheritance, so I have to embed the base ViewController's functions into VideoViewController instead of inheritance. It's an issue caused by not being careful enough when modifying code.
Topic: UI Frameworks SubTopic: UIKit
Replies
Boosts
Views
Activity
Apr ’25
Reply to App Store Connect analytics reports return 500 API error
Now I started facing another problem with pagination: next url is invalid. Get: https://api.appstoreconnect.apple.com/v1/analyticsReportRequests/{id}/relationships/reports?cursor=Mg Error: { errors: [ { id: 56e0cfab-4e86-4e4b-9a12-d76277ad9f94, status: 400, code: PARAMETER_ERROR.INVALID, title: A parameter has an invalid value, detail: 'Mg' is not a valid cursor for this request, source: { parameter: cursor } } ] }
Replies
Boosts
Views
Activity
Apr ’25
SwiftData Many-To-Many Relationship: Failed to fulfill link PendingRelationshipLink
Hi there, I got two models here: Two Models, with Many-To-Many Relationship @Model final class PresetParams: Identifiable { @Attribute(.unique) var id: UUID = UUID() var positionX: Float = 0.0 var positionY: Float = 0.0 var positionZ: Float = 0.0 var volume: Float = 1.0 @Relationship(deleteRule: .nullify, inverse: Preset.presetAudioParams) var preset = [Preset]() init(position: SIMD3, volume: Float) { self.positionX = position.x self.positionY = position.y self.positionZ = position.z self.volume = volume self.preset = [] } var position: SIMD3 { get { return SIMD3(x: positionX, y: positionY, z: positionZ) } set { positionX = newValue.x positionY = newValue.y positionZ = newValue.z } } } @Model final class Preset: Identifiable { @Attribute(.unique) var id: UUID = UUID() var presetName: String var presetDesc: String? var presetAudioParams = [PresetParams]() // Many-To-Many Relationship. init(presetName: String, presetDesc: String? = nil) { self.presetName = presetName self.presetDesc =
Replies
1
Boosts
0
Views
160
Activity
Apr ’25
Reply to SwiftData Many-To-Many Relationship: Failed to fulfill link PendingRelationshipLink
Do you have a minimal sample with detailed steps that reproduce the issue? The way you defined the relationship looks good to me, and so a runnable project may help diagnose the issue. Your post can contain a link to where your test project is hosted. Best, —— Ziqiao Chen  Worldwide Developer Relations.
Replies
Boosts
Views
Activity
Apr ’25
error: the replacement path doesn't exist <- how bad is this error, should i care - is it important?
I get this error, i have my own DIKit, and i want to use swiftdata for showing info from persisten model. It works all over the app, but i get this error with my .sheet. // JobCreationView.swift // Features // // Created by Jens Vik on 26/03/2025. // import SwiftUI import DesignKit import DIKit import PresentationKit import CoreKit import DomainKit import SwiftData public struct JobCreationView: View { @Binding var isPresented: Bool // Inject view model using DIKit's property wrapper @Injected((any JobCreationViewModelProtocol).self) private var viewModel // Form state @Injected(ModelContext.self) private var modelContext @State private var date = Date() @State private var isASAP = false @State private var price = @State private var jobType = Fiks @State private var description = // Available job types private let jobTypes = [Fiks, Fiksit] @Query private var userContexts: [UserContextModel] public init(isPresented: Binding) { self._isPresented = isPresented print(DEBUG: JobCreationView ini
Replies
1
Boosts
0
Views
124
Activity
Apr ’25