Search results for

“SwiftData inheritance relationship”

4,982 results found

Post

Replies

Boosts

Views

Activity

Reply to Swift existential types: how to create generic Views that conform to a protcol ?
One possible solution to this is to use composition instead of inheritance. The approach is detailed here https://stackoverflow.com/a/77250029/663360 and it works. However, for my own understanding, I still wonder how an inheritance pattern would work. I understand Swift resolves types at compile time (vs Objective-C, Java, Python, Typescript) and that prevents using existential types. Is there a way to solve my problem through inheritance and protocols ?
Topic: UI Frameworks SubTopic: SwiftUI Tags:
Oct ’23
ModelActors not persisting relationships in iOS 18 beta
I've already submitted this as a bug report to Apple, but I am posting here so others can save themselves some troubleshooting. This is submitted as FB14337982 with an attached complete Xcode project to replicate. In iOS 17 we use a ModelActor to download data which is saved as an Event, and then save it to SwiftData with a relationship to a Location. In iOS 18 22A5307d we are seeing that this code no longer persists the relationship to the Location, but still saves the Event. If we put a breakpoint in that ModelActor we see that the object graph is correct within the ModelActor stack trace at the time we call modelContext.save(). However, after saving, the relationship is missing from the default.store SQLite file, and of course from the app UI. Here is a toy example showing how inserting an Employee into a Company using a ModelActor gives unexpected results in iOS 18 22A5307d but works as expected in iOS 17. It appears that no relationships data survives being sa
9
0
1.4k
Jul ’24
Reply to Why am I getting infinite recursion with ==
>> how to reference an inherited ==You can't. In this case, you can't because Card is a value type and there is no inheritance.For a class (reference) type, you still can't inherit the function because the Equatable protocol requires it to be static, which implies final. Therefore this function isn't overridable.If you wanted to inherit a complicated equality check, the correct way would be to put the code in a regular method in the superclass, and invoke (and/or overrid) this method in the subclass.
Topic: Programming Languages SubTopic: Swift Tags:
May ’17
Reply to Random "duplicate column name" crashes using SwiftData
I had the exact same problem. On the first startup everything is ok, then on the second one it crashes. It seems SwiftData doesn't see the already existing column for one-to-many relationship. This, in turn, crashes the application because of the duplicated column. The solution that I found is to explicitly create the inverse relationship in the second model. So, in your case, changing your DeskPosition model to this: @Model final class DeskPosition { let id: UUID var title: String var desk: Desk? private var heightInCm: Double @Transient var height: DeskHeight { get { DeskHeight(value: heightInCm, unit: .centimeters).localized } set { heightInCm = newValue.converted(to: .centimeters).value } } init(id: UUID, height: DeskHeight, title: String) { self.id = id self.heightInCm = height.converted(to: .centimeters).value self.title = title self.height = height } }
Oct ’23
SwiftData Fatal error
I'm developing an app that uses CloudKit synchronization with SwiftData and on visionOS I added an App Settings bundle. I have noticed that sometimes, when the app is open and the user changes a setting from the App Settings bundle, the following fatal error occurs: SwiftData/BackingData.swift:831: Fatal error: This model instance was destroyed by calling ModelContext.reset and is no longer usable. The setting is read within the App struct in the visionOS app target using @AppStorage and this value is in turn used to set the passthrough video dimming via the .preferredSurroundingsEffect modifier. The setting allows the user to specify the dimming level as dark, semi dark, or ultra dark. The fatal error appears to occur intermittently although the first time it was observed was after adding the settings bundle. As such, I suspect there is some connection between those code changes and this fatal error even though they do not directly relate to SwiftData.
1
0
287
Sep ’25
Reply to SwiftData relationshipKeyPathsForPrefetching not working
It looks like I can work around part of the problem by executing the fetch for the related models directly. SwiftData will then properly use them as a cache. // Fetch accounts var fd = FetchDescriptor() let accounts = modelContext.fetch(fd) // CoreData: sql: SELECT 0, t0.Z_PK, t0.Z_OPT, t0.ZACCOUNTID FROM ZACCOUNT t0 // CoreData: sql: SELECT 0, t0.Z_PK, t0.Z_OPT, t0.ZORDERID, t0.ZTIMESTAMP, t0.ZACCOUNT, t0.ZORDERITEMS FROM ZORDER t0 WHERE t0.ZACCOUNT IN (SELECT * FROM _Z_intarray0) ORDER BY t0.ZACCOUNT // Fetch related orders for accounts let accArray = accounts.map { $0.persistentModelID } var fd2 = FetchDescriptor() fd2.predicate = #Predicate { if let account = $0.account { accArray.contains(account.persistentModelID) } else { false } } let orders = try? modelContext.fetch(fd2) // CoreData: sql: SELECT 0, t0.Z_PK, t0.Z_OPT, t0.ZORDERID, t0.ZTIMESTAMP, t0.ZACCOUNT, t0.ZORDERITEMS FROM ZORDER t0 WHERE (CASE ((CASE ( t0.ZACCOUNT IS NOT NULL) when 1 then ((CASE ( t0.ZACCOUNT IN (SELECT * FROM _Z_intarr
Mar ’25
Preserving Core Data relationships in a merge policy
I am trying to merge a Core Data object with a unique constraint while preserving relationships. In particular, I am trying to avoid overwriting a relationship with nil.The relationship is optional, but the inverse is mandatory. As such, the delete rule is set to “Cascade”, which makes it particularly important that it doesn’t get wiped.I’m using the following custom merge policy, and it seems to work… at first. Before saving is complete, the following warning gets printed to the console: `CoreData: annotation: repairing missing delete propagation for to-one relationship […] on object […] with bad fault […]`. Core Data seems to deliberately erase anything I try to preserve. What is causing that, and how can I stop it?private class NSMergeByPropertyNonNilObjectTrumpMergePolicy: NSMergePolicy { override func resolve(constraintConflicts list: [NSConstraintConflict]) throws { try super.resolve(constraintConflicts: list.compactMap { conflict in // don't customize context-level h
1
0
1.7k
Apr ’20
SwiftData and iCloud
I'm a first time developer for Swift, (getting on a bit!) but after programming in VB back in the late 90s I wanted to write an app for iPhone. I think I might have gone about it the wrong way, but I've got an app that works great on my iPhone or works great on my iPad. It saves the data persistently on device, but, no matter how much I try, what I read and even resorting to AI (ChatGPT & Gemini) I still can't get it to save the data on iCloud to synchronise between the two and work across the devices. I think it must be something pretty fundamental I'm doing (or more likely not doing) that is causing the issue. I'm setting up my signing and capabilities as per the available instructions but I always get a fatal error. I think it might be something to do with making fields optional, but at this point I'm second guessing myself and feeling a complete failure. Any advice or pointers would be really gratefully appreciated. I like my app and would like eventually to get it on the App Store but at this point i
2
0
197
Apr ’25
App crashes because of SwiftData
I was implementing SwiftData on my app and everything works on emulator (both iOS and iPadOS). But when I try to run it on my device, it threw an error dyld[548]: Symbol not found: _$s9SwiftData15PropertyOptionsC6uniqueACvgZ Referenced from: <5E19B2FA-C3D5-353E-AEE7-7B31B7BE56B4> /private/var/containers/Bundle/Application/F7269758-C6E1-46DA-A6E2-8AD5EBB54CFF/MyApp.app/MyApp Expected in: <8B52C2B3-931A-3736-B357-ECF87A41F3EB> /System/Library/Frameworks/SwiftData.framework/SwiftData My devices are on iOS 17 Beta 6 and Xcode 15 beta 6.
12
0
2.4k
Aug ’23
Having difficulty connecting relationships during a data import
I'm trying to import some basic stop data for the trains in Chicago and there are two different custom Core Data types that I'm using to represent that data. There are Station objects and Stop objects. The Station objects represent an entire station and the Stop objects represent a grouping of directions that exist within a Station. The only relationships in the store are a many-one from Station to Stop (each station can have multiple groupings of directions in it, whereas each Stop can only belong to one station.) I'm getting four main intermittent errors with my current code being related crashes (EXC_Bad Access, for example), heap corruption relating to malloc_error_break, NSCFSet being mutated whilst being enumerated, and CoreData: error: SQLCore dispatchRequest: exception handling request: , Objects should not be both modified and additional with userInfo of (null) when I try to save the context. Here is my current code that fetches the station data and performs a batch insert into Core Data. s
1
0
1.5k
Jan ’23
SwiftData assertionFailure crash in release builds?
I have an issue in my app, where the crashing frame is an assertionFailure in BackingData.set inside SwiftData framework. My own app doesn't appear until frame 14. I have no idea what causes this, or even how to create a reproducible project as this only happens on some devices. The frame prior to the assertionFailure is this: #1 (null) in BackingData.set(any:value:) () It seems like there is a backing data encoding happening in my Model class, and some value is causing it to fail. The model being accessed is through a relationship, and the frame in the app crashing is along the lines of Text(parent.child.name) Obviously, something is wrong in how I have made child, but the part that stand out to me is the assertionFailure in a release build
4
0
127
Apr ’25
Does SwiftData have a context.perform {} method?
Does SwiftData have a method like CoreData's context.perform {} context.performAndWait {}? I execute it in an asynchronous thread, context.insert(userBook), and get an error message Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Illegal attempt to establish a relationship 'user' between objects in different contexts (source = (entity: UserBookEntity; id: 0x6000003366e0 ; I define a base Repo struct BaseRepo { static let shared = BaseRepo() var container: ModelContainer? var context: ModelContext? let fullModelList: [any PersistentModel.Type] = [ DomainDict.self, User.self, UserBookEntity.self, Book.self, Category.self ] init() { do{ container = try ModelContainer(for: fullModelList) if let container { context = ModelContext(container) } } catch{ print(error) } } } then I save data ,but get an error,It shows that I am not in the same context, but I pass in the same context func saveBookData(bookData: FetchBookData,uid: String) -> Future { return Future {
2
0
1.2k
Jul ’23
SwiftData Model Container for Many Classes
Hi, Most of SwiftData tutorials use one SwiftData Class model though defining it is modelContainer is straightforward, what if I have say 10 model classes how to define them in the modelContainer ? Kind Regards
Replies
0
Boosts
0
Views
417
Activity
Jun ’24
Reply to Swift existential types: how to create generic Views that conform to a protcol ?
One possible solution to this is to use composition instead of inheritance. The approach is detailed here https://stackoverflow.com/a/77250029/663360 and it works. However, for my own understanding, I still wonder how an inheritance pattern would work. I understand Swift resolves types at compile time (vs Objective-C, Java, Python, Typescript) and that prevents using existential types. Is there a way to solve my problem through inheritance and protocols ?
Topic: UI Frameworks SubTopic: SwiftUI Tags:
Replies
Boosts
Views
Activity
Oct ’23
ModelActors not persisting relationships in iOS 18 beta
I've already submitted this as a bug report to Apple, but I am posting here so others can save themselves some troubleshooting. This is submitted as FB14337982 with an attached complete Xcode project to replicate. In iOS 17 we use a ModelActor to download data which is saved as an Event, and then save it to SwiftData with a relationship to a Location. In iOS 18 22A5307d we are seeing that this code no longer persists the relationship to the Location, but still saves the Event. If we put a breakpoint in that ModelActor we see that the object graph is correct within the ModelActor stack trace at the time we call modelContext.save(). However, after saving, the relationship is missing from the default.store SQLite file, and of course from the app UI. Here is a toy example showing how inserting an Employee into a Company using a ModelActor gives unexpected results in iOS 18 22A5307d but works as expected in iOS 17. It appears that no relationships data survives being sa
Replies
9
Boosts
0
Views
1.4k
Activity
Jul ’24
Reply to Why am I getting infinite recursion with ==
>> how to reference an inherited ==You can't. In this case, you can't because Card is a value type and there is no inheritance.For a class (reference) type, you still can't inherit the function because the Equatable protocol requires it to be static, which implies final. Therefore this function isn't overridable.If you wanted to inherit a complicated equality check, the correct way would be to put the code in a regular method in the superclass, and invoke (and/or overrid) this method in the subclass.
Topic: Programming Languages SubTopic: Swift Tags:
Replies
Boosts
Views
Activity
May ’17
Reply to Random "duplicate column name" crashes using SwiftData
I had the exact same problem. On the first startup everything is ok, then on the second one it crashes. It seems SwiftData doesn't see the already existing column for one-to-many relationship. This, in turn, crashes the application because of the duplicated column. The solution that I found is to explicitly create the inverse relationship in the second model. So, in your case, changing your DeskPosition model to this: @Model final class DeskPosition { let id: UUID var title: String var desk: Desk? private var heightInCm: Double @Transient var height: DeskHeight { get { DeskHeight(value: heightInCm, unit: .centimeters).localized } set { heightInCm = newValue.converted(to: .centimeters).value } } init(id: UUID, height: DeskHeight, title: String) { self.id = id self.heightInCm = height.converted(to: .centimeters).value self.title = title self.height = height } }
Replies
Boosts
Views
Activity
Oct ’23
SwiftData Fatal error
I'm developing an app that uses CloudKit synchronization with SwiftData and on visionOS I added an App Settings bundle. I have noticed that sometimes, when the app is open and the user changes a setting from the App Settings bundle, the following fatal error occurs: SwiftData/BackingData.swift:831: Fatal error: This model instance was destroyed by calling ModelContext.reset and is no longer usable. The setting is read within the App struct in the visionOS app target using @AppStorage and this value is in turn used to set the passthrough video dimming via the .preferredSurroundingsEffect modifier. The setting allows the user to specify the dimming level as dark, semi dark, or ultra dark. The fatal error appears to occur intermittently although the first time it was observed was after adding the settings bundle. As such, I suspect there is some connection between those code changes and this fatal error even though they do not directly relate to SwiftData.
Replies
1
Boosts
0
Views
287
Activity
Sep ’25
Reply to SwiftData relationshipKeyPathsForPrefetching not working
It looks like I can work around part of the problem by executing the fetch for the related models directly. SwiftData will then properly use them as a cache. // Fetch accounts var fd = FetchDescriptor() let accounts = modelContext.fetch(fd) // CoreData: sql: SELECT 0, t0.Z_PK, t0.Z_OPT, t0.ZACCOUNTID FROM ZACCOUNT t0 // CoreData: sql: SELECT 0, t0.Z_PK, t0.Z_OPT, t0.ZORDERID, t0.ZTIMESTAMP, t0.ZACCOUNT, t0.ZORDERITEMS FROM ZORDER t0 WHERE t0.ZACCOUNT IN (SELECT * FROM _Z_intarray0) ORDER BY t0.ZACCOUNT // Fetch related orders for accounts let accArray = accounts.map { $0.persistentModelID } var fd2 = FetchDescriptor() fd2.predicate = #Predicate { if let account = $0.account { accArray.contains(account.persistentModelID) } else { false } } let orders = try? modelContext.fetch(fd2) // CoreData: sql: SELECT 0, t0.Z_PK, t0.Z_OPT, t0.ZORDERID, t0.ZTIMESTAMP, t0.ZACCOUNT, t0.ZORDERITEMS FROM ZORDER t0 WHERE (CASE ((CASE ( t0.ZACCOUNT IS NOT NULL) when 1 then ((CASE ( t0.ZACCOUNT IN (SELECT * FROM _Z_intarr
Replies
Boosts
Views
Activity
Mar ’25
Preserving Core Data relationships in a merge policy
I am trying to merge a Core Data object with a unique constraint while preserving relationships. In particular, I am trying to avoid overwriting a relationship with nil.The relationship is optional, but the inverse is mandatory. As such, the delete rule is set to “Cascade”, which makes it particularly important that it doesn’t get wiped.I’m using the following custom merge policy, and it seems to work… at first. Before saving is complete, the following warning gets printed to the console: `CoreData: annotation: repairing missing delete propagation for to-one relationship […] on object […] with bad fault […]`. Core Data seems to deliberately erase anything I try to preserve. What is causing that, and how can I stop it?private class NSMergeByPropertyNonNilObjectTrumpMergePolicy: NSMergePolicy { override func resolve(constraintConflicts list: [NSConstraintConflict]) throws { try super.resolve(constraintConflicts: list.compactMap { conflict in // don't customize context-level h
Replies
1
Boosts
0
Views
1.7k
Activity
Apr ’20
SwiftData and iCloud
I'm a first time developer for Swift, (getting on a bit!) but after programming in VB back in the late 90s I wanted to write an app for iPhone. I think I might have gone about it the wrong way, but I've got an app that works great on my iPhone or works great on my iPad. It saves the data persistently on device, but, no matter how much I try, what I read and even resorting to AI (ChatGPT & Gemini) I still can't get it to save the data on iCloud to synchronise between the two and work across the devices. I think it must be something pretty fundamental I'm doing (or more likely not doing) that is causing the issue. I'm setting up my signing and capabilities as per the available instructions but I always get a fatal error. I think it might be something to do with making fields optional, but at this point I'm second guessing myself and feeling a complete failure. Any advice or pointers would be really gratefully appreciated. I like my app and would like eventually to get it on the App Store but at this point i
Replies
2
Boosts
0
Views
197
Activity
Apr ’25
SwiftData Equivalent of @SectionedFetchRequest
Hi all, Has anyone stumbled upon the SwiftData equivalent of @SectionedFetchRequest? Is there a way to do it with @Query? I'll keep going through the documentation but if anyone has an answer, it would be much appreciated!! Thank you.
Replies
5
Boosts
0
Views
2.5k
Activity
Jun ’23
App crashes because of SwiftData
I was implementing SwiftData on my app and everything works on emulator (both iOS and iPadOS). But when I try to run it on my device, it threw an error dyld[548]: Symbol not found: _$s9SwiftData15PropertyOptionsC6uniqueACvgZ Referenced from: <5E19B2FA-C3D5-353E-AEE7-7B31B7BE56B4> /private/var/containers/Bundle/Application/F7269758-C6E1-46DA-A6E2-8AD5EBB54CFF/MyApp.app/MyApp Expected in: <8B52C2B3-931A-3736-B357-ECF87A41F3EB> /System/Library/Frameworks/SwiftData.framework/SwiftData My devices are on iOS 17 Beta 6 and Xcode 15 beta 6.
Replies
12
Boosts
0
Views
2.4k
Activity
Aug ’23
Having difficulty connecting relationships during a data import
I'm trying to import some basic stop data for the trains in Chicago and there are two different custom Core Data types that I'm using to represent that data. There are Station objects and Stop objects. The Station objects represent an entire station and the Stop objects represent a grouping of directions that exist within a Station. The only relationships in the store are a many-one from Station to Stop (each station can have multiple groupings of directions in it, whereas each Stop can only belong to one station.) I'm getting four main intermittent errors with my current code being related crashes (EXC_Bad Access, for example), heap corruption relating to malloc_error_break, NSCFSet being mutated whilst being enumerated, and CoreData: error: SQLCore dispatchRequest: exception handling request: , Objects should not be both modified and additional with userInfo of (null) when I try to save the context. Here is my current code that fetches the station data and performs a batch insert into Core Data. s
Replies
1
Boosts
0
Views
1.5k
Activity
Jan ’23
Reply to Subclass extension for superclasses
But then I cannot inherit from A!
Topic: Programming Languages SubTopic: Swift Tags:
Replies
Boosts
Views
Activity
Apr ’22
SwiftData assertionFailure crash in release builds?
I have an issue in my app, where the crashing frame is an assertionFailure in BackingData.set inside SwiftData framework. My own app doesn't appear until frame 14. I have no idea what causes this, or even how to create a reproducible project as this only happens on some devices. The frame prior to the assertionFailure is this: #1 (null) in BackingData.set(any:value:) () It seems like there is a backing data encoding happening in my Model class, and some value is causing it to fail. The model being accessed is through a relationship, and the frame in the app crashing is along the lines of Text(parent.child.name) Obviously, something is wrong in how I have made child, but the part that stand out to me is the assertionFailure in a release build
Replies
4
Boosts
0
Views
127
Activity
Apr ’25
Does SwiftData have a context.perform {} method?
Does SwiftData have a method like CoreData's context.perform {} context.performAndWait {}? I execute it in an asynchronous thread, context.insert(userBook), and get an error message Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Illegal attempt to establish a relationship 'user' between objects in different contexts (source = (entity: UserBookEntity; id: 0x6000003366e0 ; I define a base Repo struct BaseRepo { static let shared = BaseRepo() var container: ModelContainer? var context: ModelContext? let fullModelList: [any PersistentModel.Type] = [ DomainDict.self, User.self, UserBookEntity.self, Book.self, Category.self ] init() { do{ container = try ModelContainer(for: fullModelList) if let container { context = ModelContext(container) } } catch{ print(error) } } } then I save data ,but get an error,It shows that I am not in the same context, but I pass in the same context func saveBookData(bookData: FetchBookData,uid: String) -> Future { return Future {
Replies
2
Boosts
0
Views
1.2k
Activity
Jul ’23