Search results for

“SwiftData inheritance relationship”

4,981 results found

Post

Replies

Boosts

Views

Activity

Can't add values to Relationship?
Hi There, i'm not sure if anything changed in Beta 7 or it's me being an idiot but I can't seem to update my relationship property, anyone else experienced this? @Model final class Goal { // More properties here @Relationship(deleteRule: .cascade, inverse: Progress.goal) var progress: [Progress]? init(progress: [Progress]? = []) { self.progress = progress } func updateProgress(with value: Double) { // I've also tried this with having the modelContext in the initialiser let context = ModelContext(DataStore.container) let newProgress = Progress(date: Date.now, value: value) newProgress.goal = self context.insert(newProgress) self.progress?.append(newProgress) // Other code } } @Model final class Progress { var progressDate: Date? var value: Double? var goal: Goal? init(date: Date = Date.now, value: Double = 0.0, goal: Goal? = nil) { self.progressDate = date self.value = value self.goal = goal } } Everytime I call the updateProgress method I get a fatal error (e.g. goal.updateProgress(with: 33.
3
0
1.3k
Aug ’23
SectionedFetchRequest in SwiftData
With Core Data and SwiftUI we can use @SectionedFetchRequest. Does SwiftData support something similar to @SectionedFetchRequest? For example, I want to create a lazy-loaded list that groups posts by their date. @Model Post { let title: String let dateString: String // YYYY-MM-DD let createdAt: Date } @SectionedFetchRequest( entity: Post.self, sectionIdentifier: Post.dateString, sortDescriptors: [Post.createdAt] ) var postsByDate: SectionedFetchResults ForEach(postsByDate) { section in Section(header: Text(section.id)) { ForEach(section) { post in PostView(post) } } }
2
0
537
Sep ’24
How to deduplicate entities with relationships in NSPersistentCloudKitContainer?
In my app I have a defaultJournal: Journal, that automatically gets added on the user's device on launch. There should only be one default journal, and I know that deduplication as shown in the Apple Demo, is the correct approach to ensure this on multiple devices. Journal looks something like: class Journal: NSManagedObject { @NSManaged var isDefaultJournal: Bool @NSManaged var entries: Set? } Since Journal has a relationship to entries, how can I deduplicate it ensuring that I don't orphan or delete the entries? I am worried that the entries aren't guaranteed to be synced, when we discover a duplicate journal in processPersistentHistory. This would lead to either orphaned or deleted entries depending on the deletion rule. How can one handle deduplicating entities with relationships? For example here is my remove function: func remove(duplicateDefaultCalendarNotes: [Journal], winner: Journal, on context: NSManagedObjectContext) { duplicateDefaultCalendarNotes.forEach { journal in defer { co
1
0
1.2k
Oct ’21
how to make 2-depth parameter relationship
i'm trying to create a custom shortcuts app action.https://developer.apple.com/documentation/sirikit/adding_user_interactivity_with_siri_shortcuts_and_the_shortcuts_appin section Establish Relationships Between ParametersI want to make the 2-depth relationship (show if parent) between parameters.but, I think the xcode ide supports only 1-depth relationship.how to make belows?example) Do not disturb ${enable} until ${until} ${time}:CUSTOM_TYPEenum 'enable' - [on | off]enum 'until' - [turned off | time]:RELATIONrelation 'show if parent has exact value'until -> enable:ontime -> until:timeDo not distrub {off}Do not distrub {on} until {turned off}Do not distrub {on} until {time} {2022/06/01}
1
0
486
May ’20
Reply to SwiftData & CloudKit: Arrays of Codable Structs Causing NSKeyedUnarchiveFromData Error
Do you have a feedback report yet? If not, I’d suggest that you file one and share your report ID here. For a workaround, you might consider making SchedulingTime a SwiftData model, if that is appropriate, and relating it to ProtocolMedication with a too-many relationship. You can also consider using Data directly for persistence, and providing a transient (@Transient) property for the access to the struct array (only) in memory. A transient property can't be used in a query though. Best, —— Ziqiao Chen  Worldwide Developer Relations.
Topic: UI Frameworks SubTopic: SwiftUI Tags:
Sep ’25
Ordered one-to-many relationships
Hi,I would like to address this issue (http://stackoverflow.com/questions/7385439/exception-thrown-in-nsorderedset-generated-accessors).The problem is that when I set a one-to-many relationship to be ordered in model definition, I receive a runtime exception.I did not find any topic here related to this issue, so I am creating one here.As you can see, this issue persists for many years in CoreData.
1
0
353
Sep ’15
Many-to-one relationship can't be unlinked
I am using NSPersistentCloudKitContainer, and have a many-to-one optional relationship, let say many item to one project.This relationship is optional, so I can do this ->item.project = nilwhen the user decided that this item does not belongs to any project.This code is fine in Core Data, and the inverse relationships are updated accordingly.However, once this gets synced to CloudKit, and come back down, the project relationship will be restored. Setting the project to other entities are fine, it just cannot be set to nil.Playing with the CloudKit dashboard, I realized that the schema that is created have a CD_Project as String. If I create a new item without any project, there's no such field, however, once I assign a project to an item, the field is set, and there is no way to unset this field, even from the CloudKit Dashboard. I naively tried to clear out the string in cloudkit dashboard but it crashes my app when the sync happens.Is this a bug that will be fixed? The
3
0
1.4k
Jan ’20
SwiftData public sharing
I have an Apple app that uses SwiftData and icloud to sync the App's data across users' devices. Everything is working well. However, I am facing the following issue: SwiftData does not support public sharing of the object graph with other users via iCloud. How can I overcome this limitation without stopping using SwiftData? Thanks in advance!
2
0
734
May ’24
Reply to Importing Data into SwiftData in the Background Using ModelActor and @Query
I'm writing to express my frustration and disbelief that this critical bug is still present in production as of 2026. We just completed a major refactoring effort, migrating our application from iCloud-based static file storage to SwiftData with CloudKit sync. During this migration, we encountered this exact issue and was stunned to discover it was already documented in 2024. Here one of several specific scenarios: Logbook view structure: @Bindable var logbook: Logbook (where Logbook is a @Model class) The logbook.flights relationship array is not observed - changes to the array don't trigger view updates Attempted workaround using @Query var flights: [Flight] - still not observed This affects one of our primary user-facing views (flight logbook table) Why the suggested workaround doesn't work: The proposed solution of triggering refreshes on modelContext.didSave notifications is impractical for real-world applications: • Context saves can occur multiple times throughout the app's lifecycle
Feb ’26
Core Data relationship question
I'm looking to understand the connection between relationships in core data. What I'm trying to do is store two entities 'Workout' and 'Exercise' and allow multiple 'Exercises' to one 'Workout'. Im'm coming from a MYSQL background so it's a little fuzzy when it comes to the relation.How would I be able to keep the reference to the workout object, use some variable to store the objectID and then use it to update the exercise entity?Thanks
1
0
429
Dec ’16
CloudKit is not synchronizing with coredata for relationships
In core-data I have a contact and location entity. I have one-to-many relationship from contact to locations and one-to-one from location to contact. I create contact in a seperate view and save it. Later I create a location, fetch the created contact, and save it while specifying the relationship between location and contact contact and test if it actually did it and it works. viewContext.perform { do { // Set relationship using the generated accessor method currentContact.addToLocations(location) try viewContext.save() print(Saved successfully. Locations count:, currentContact.locations?.count ?? 0) if let locs = currentContact.locations { print(📍 Contact has (locs.count) locations.) for loc in locs { print(➡️ Location: (String(describing: (loc as AnyObject).locationName ?? Unnamed))) } } } catch { print(Failed to save location: (error.localizedDescription)) } } In my NSManagedObject class properties I have this : for Contact: @NSManaged public var locations: NSSet? for Location:
0
0
128
Apr ’25
SwiftData update value
Hi I want to update item value after insert. Solution(False): I want to add isAutosaveEnabled prop to modelContainer, but modelContainer just have one parm. Solution2(False): There doesn't have API to update SwiftData, I just find insert, delete and save. I change the city_name and run try? modelContext.save(). But it replace after I reopen the app and maybe it doesn't work even before I close app. How can I update the city_name? /// --------- App --------- import SwiftUI import SwiftData @main struct MyApp: App { var container: ModelContainer init(){ let schema = Schema([ SD_City.self, ]) let modelConfiguration = ModelConfiguration(schema: schema) do { container = try ModelContainer(for: schema, configurations: [modelConfiguration]) let context = ModelContext(container) var city : SD_City city = SD_City(city_id: 1, city_name: city1) context.insert(city) city = SD_City(city_id: 2, city_name: city2) context.insert(city) } catch { fatalError(Could not create ModelContainer: ) } } var body: som
0
0
436
Jul ’24
SwiftData
As soon as I invoke a call for import SwiftData I am getting this error Linker command failed with exit code 1 (use -v to see invocation) Before deleting, I went to the Library Directory and manually Deleted the directory of Developer. And then I proceeded to deleted Xcode beta 3 and downloaded a fresh beta 2 and I still have the same error. I even deleted beta 2 and reinstall beta 1 and still the same error. Can someone give me any direction please Robert Update: I erased the hard drive and installed a Fresh MacOS 13.4.1 with a Fresh never ran Xcode beta 3 and right away as soon as I ran it the first time, I am having the same problem. WHAT IS GOING ON???
0
0
443
Jul ’23
Can't add values to Relationship?
Hi There, i'm not sure if anything changed in Beta 7 or it's me being an idiot but I can't seem to update my relationship property, anyone else experienced this? @Model final class Goal { // More properties here @Relationship(deleteRule: .cascade, inverse: Progress.goal) var progress: [Progress]? init(progress: [Progress]? = []) { self.progress = progress } func updateProgress(with value: Double) { // I've also tried this with having the modelContext in the initialiser let context = ModelContext(DataStore.container) let newProgress = Progress(date: Date.now, value: value) newProgress.goal = self context.insert(newProgress) self.progress?.append(newProgress) // Other code } } @Model final class Progress { var progressDate: Date? var value: Double? var goal: Goal? init(date: Date = Date.now, value: Double = 0.0, goal: Goal? = nil) { self.progressDate = date self.value = value self.goal = goal } } Everytime I call the updateProgress method I get a fatal error (e.g. goal.updateProgress(with: 33.
Replies
3
Boosts
0
Views
1.3k
Activity
Aug ’23
SectionedFetchRequest in SwiftData
With Core Data and SwiftUI we can use @SectionedFetchRequest. Does SwiftData support something similar to @SectionedFetchRequest? For example, I want to create a lazy-loaded list that groups posts by their date. @Model Post { let title: String let dateString: String // YYYY-MM-DD let createdAt: Date } @SectionedFetchRequest( entity: Post.self, sectionIdentifier: Post.dateString, sortDescriptors: [Post.createdAt] ) var postsByDate: SectionedFetchResults ForEach(postsByDate) { section in Section(header: Text(section.id)) { ForEach(section) { post in PostView(post) } } }
Replies
2
Boosts
0
Views
537
Activity
Sep ’24
How to deduplicate entities with relationships in NSPersistentCloudKitContainer?
In my app I have a defaultJournal: Journal, that automatically gets added on the user's device on launch. There should only be one default journal, and I know that deduplication as shown in the Apple Demo, is the correct approach to ensure this on multiple devices. Journal looks something like: class Journal: NSManagedObject { @NSManaged var isDefaultJournal: Bool @NSManaged var entries: Set? } Since Journal has a relationship to entries, how can I deduplicate it ensuring that I don't orphan or delete the entries? I am worried that the entries aren't guaranteed to be synced, when we discover a duplicate journal in processPersistentHistory. This would lead to either orphaned or deleted entries depending on the deletion rule. How can one handle deduplicating entities with relationships? For example here is my remove function: func remove(duplicateDefaultCalendarNotes: [Journal], winner: Journal, on context: NSManagedObjectContext) { duplicateDefaultCalendarNotes.forEach { journal in defer { co
Replies
1
Boosts
0
Views
1.2k
Activity
Oct ’21
how to make 2-depth parameter relationship
i'm trying to create a custom shortcuts app action.https://developer.apple.com/documentation/sirikit/adding_user_interactivity_with_siri_shortcuts_and_the_shortcuts_appin section Establish Relationships Between ParametersI want to make the 2-depth relationship (show if parent) between parameters.but, I think the xcode ide supports only 1-depth relationship.how to make belows?example) Do not disturb ${enable} until ${until} ${time}:CUSTOM_TYPEenum 'enable' - [on | off]enum 'until' - [turned off | time]:RELATIONrelation 'show if parent has exact value'until -> enable:ontime -> until:timeDo not distrub {off}Do not distrub {on} until {turned off}Do not distrub {on} until {time} {2022/06/01}
Replies
1
Boosts
0
Views
486
Activity
May ’20
Reply to getting error with the client server walkthrough on the development guide
Thank you, I was wondering if it was an inherited property of something that I wasn't inheriting or what.
Topic: App & System Services SubTopic: Core OS Tags:
Replies
Boosts
Views
Activity
Sep ’15
Reply to SwiftData & CloudKit: Arrays of Codable Structs Causing NSKeyedUnarchiveFromData Error
Do you have a feedback report yet? If not, I’d suggest that you file one and share your report ID here. For a workaround, you might consider making SchedulingTime a SwiftData model, if that is appropriate, and relating it to ProtocolMedication with a too-many relationship. You can also consider using Data directly for persistence, and providing a transient (@Transient) property for the access to the struct array (only) in memory. A transient property can't be used in a query though. Best, —— Ziqiao Chen  Worldwide Developer Relations.
Topic: UI Frameworks SubTopic: SwiftUI Tags:
Replies
Boosts
Views
Activity
Sep ’25
Ordered one-to-many relationships
Hi,I would like to address this issue (http://stackoverflow.com/questions/7385439/exception-thrown-in-nsorderedset-generated-accessors).The problem is that when I set a one-to-many relationship to be ordered in model definition, I receive a runtime exception.I did not find any topic here related to this issue, so I am creating one here.As you can see, this issue persists for many years in CoreData.
Replies
1
Boosts
0
Views
353
Activity
Sep ’15
Many-to-one relationship can't be unlinked
I am using NSPersistentCloudKitContainer, and have a many-to-one optional relationship, let say many item to one project.This relationship is optional, so I can do this ->item.project = nilwhen the user decided that this item does not belongs to any project.This code is fine in Core Data, and the inverse relationships are updated accordingly.However, once this gets synced to CloudKit, and come back down, the project relationship will be restored. Setting the project to other entities are fine, it just cannot be set to nil.Playing with the CloudKit dashboard, I realized that the schema that is created have a CD_Project as String. If I create a new item without any project, there's no such field, however, once I assign a project to an item, the field is set, and there is no way to unset this field, even from the CloudKit Dashboard. I naively tried to clear out the string in cloudkit dashboard but it crashes my app when the sync happens.Is this a bug that will be fixed? The
Replies
3
Boosts
0
Views
1.4k
Activity
Jan ’20
SwiftData public sharing
I have an Apple app that uses SwiftData and icloud to sync the App's data across users' devices. Everything is working well. However, I am facing the following issue: SwiftData does not support public sharing of the object graph with other users via iCloud. How can I overcome this limitation without stopping using SwiftData? Thanks in advance!
Replies
2
Boosts
0
Views
734
Activity
May ’24
Properly typed Core Data relationships
Is there a way to get CoreData to generate a relationship of type Set<T> instead of NSSet?
Replies
2
Boosts
0
Views
777
Activity
Aug ’17
Reply to Importing Data into SwiftData in the Background Using ModelActor and @Query
I'm writing to express my frustration and disbelief that this critical bug is still present in production as of 2026. We just completed a major refactoring effort, migrating our application from iCloud-based static file storage to SwiftData with CloudKit sync. During this migration, we encountered this exact issue and was stunned to discover it was already documented in 2024. Here one of several specific scenarios: Logbook view structure: @Bindable var logbook: Logbook (where Logbook is a @Model class) The logbook.flights relationship array is not observed - changes to the array don't trigger view updates Attempted workaround using @Query var flights: [Flight] - still not observed This affects one of our primary user-facing views (flight logbook table) Why the suggested workaround doesn't work: The proposed solution of triggering refreshes on modelContext.didSave notifications is impractical for real-world applications: • Context saves can occur multiple times throughout the app's lifecycle
Replies
Boosts
Views
Activity
Feb ’26
Core Data relationship question
I'm looking to understand the connection between relationships in core data. What I'm trying to do is store two entities 'Workout' and 'Exercise' and allow multiple 'Exercises' to one 'Workout'. Im'm coming from a MYSQL background so it's a little fuzzy when it comes to the relation.How would I be able to keep the reference to the workout object, use some variable to store the objectID and then use it to update the exercise entity?Thanks
Replies
1
Boosts
0
Views
429
Activity
Dec ’16
CloudKit is not synchronizing with coredata for relationships
In core-data I have a contact and location entity. I have one-to-many relationship from contact to locations and one-to-one from location to contact. I create contact in a seperate view and save it. Later I create a location, fetch the created contact, and save it while specifying the relationship between location and contact contact and test if it actually did it and it works. viewContext.perform { do { // Set relationship using the generated accessor method currentContact.addToLocations(location) try viewContext.save() print(Saved successfully. Locations count:, currentContact.locations?.count ?? 0) if let locs = currentContact.locations { print(📍 Contact has (locs.count) locations.) for loc in locs { print(➡️ Location: (String(describing: (loc as AnyObject).locationName ?? Unnamed))) } } } catch { print(Failed to save location: (error.localizedDescription)) } } In my NSManagedObject class properties I have this : for Contact: @NSManaged public var locations: NSSet? for Location:
Replies
0
Boosts
0
Views
128
Activity
Apr ’25
SwiftData update value
Hi I want to update item value after insert. Solution(False): I want to add isAutosaveEnabled prop to modelContainer, but modelContainer just have one parm. Solution2(False): There doesn't have API to update SwiftData, I just find insert, delete and save. I change the city_name and run try? modelContext.save(). But it replace after I reopen the app and maybe it doesn't work even before I close app. How can I update the city_name? /// --------- App --------- import SwiftUI import SwiftData @main struct MyApp: App { var container: ModelContainer init(){ let schema = Schema([ SD_City.self, ]) let modelConfiguration = ModelConfiguration(schema: schema) do { container = try ModelContainer(for: schema, configurations: [modelConfiguration]) let context = ModelContext(container) var city : SD_City city = SD_City(city_id: 1, city_name: city1) context.insert(city) city = SD_City(city_id: 2, city_name: city2) context.insert(city) } catch { fatalError(Could not create ModelContainer: ) } } var body: som
Replies
0
Boosts
0
Views
436
Activity
Jul ’24
SwiftData
As soon as I invoke a call for import SwiftData I am getting this error Linker command failed with exit code 1 (use -v to see invocation) Before deleting, I went to the Library Directory and manually Deleted the directory of Developer. And then I proceeded to deleted Xcode beta 3 and downloaded a fresh beta 2 and I still have the same error. I even deleted beta 2 and reinstall beta 1 and still the same error. Can someone give me any direction please Robert Update: I erased the hard drive and installed a Fresh MacOS 13.4.1 with a Fresh never ran Xcode beta 3 and right away as soon as I ran it the first time, I am having the same problem. WHAT IS GOING ON???
Replies
0
Boosts
0
Views
443
Activity
Jul ’23