Search results for

“SwiftData inheritance relationship”

4,980 results found

Post

Replies

Boosts

Views

Activity

SwiftData and CloudKit Issues
Hi, I'm using SwiftData in my app, and I want to sent data to iCloud with CloudKit, but I found that If the user turns off my App iCloud sync function in the settings App, the local data will also be deleted. A better way is maintaining the local data, just don't connect to iCloud.How should I do that? I need guidance!!! I'm just getting started with CloudKit And I would be appreciated!
1
0
265
Nov ’25
SwiftData Migration: Objects Created in Custom Migration Aren't Persisted or Queryable (Repost)
I'm experiencing a critical issue with SwiftData custom migrations where objects created during migration appear to be inserted successfully but aren't persisted or found by queries after migration completes. The migration logs show objects being created, but subsequent queries return zero results. I'm migrating from schema version V2 to V2_5, which involves: Renaming Person class to GroupData Keeping the same data structure but changing the class name while keeping the old class. Using a custom migration stage to copy data from old to new schema Below is an extract of my two schema and migration plan: Environment: Xcode 16.0, iOS 18.0, Swift 6.0 SchemaV2 enum LinkMapV2: VersionedSchema { static let versionIdentifier: Schema.Version = .init(2, 0, 0) static var models: [any PersistentModel.Type] { [AnnotationData.self, Person.self, History.self] } @Model final class Person { @Attribute(.unique) var id: UUID var name: String var photo: String var requirement: String var statue: Bool var annotationId: U
1
0
323
Nov ’25
SwiftData Migration: Objects Created in Custom Migration Aren't Persisted or Queryable
Description: I'm experiencing a critical issue with SwiftData custom migrations where objects created during migration appear to be inserted successfully but aren't persisted or found by queries after migration completes. The migration logs show objects being created, but subsequent queries return zero results. Problem Details: I'm migrating from schema version V2 to V3, which involves: Renaming Person class to GroupData Keeping the same data structure but changing the class name Using a custom migration stage to copy data from old to new schema Migration Code: swift static let migrationV2toV3 = MigrationStage.custom( fromVersion: LinkMapV2.self, toVersion: LinkMapV3.self, willMigrate: { context in do { let persons = try context.fetch(FetchDescriptor()) print(Found (persons.count) Person objects to migrate) // ✅ Shows 11 objects for person in persons { let newGroup = LinkMapV3.GroupData( id: person.id, // Same UUID name: person.name, // ... other properties ) context.insert(newGroup) print(Inserted G
1
0
112
Nov ’25
Reply to TCC Permission Inheritance Failure: Swift Parent -> Python Child
Hi, Thank you for the clarification request. You are correct in your assumption. 1. Daemon Clarification We are using the term daemon in the general sense of a persistent background helper process, not a system-wide launchd daemon (it is not registered in /Library/LaunchDaemons or managed by SMAppService). 2. Child Process (Python) Launch The Python process is launched directly as a child process of the main Swift application. As detailed in the Python Daemon Launch section of our document, we are using Swift's high-level Process API (which, as you noted, is layered on top of technologies like posix_spawn). The specific code used is: let process = Process() process.executableURL = URL(fileURLWithPath: pythonExecutablePath) // path is AthenaSentry.app/Contents/Helpers/AthenaSentry.app/Contents/MacOS/AthenaSentry process.environment = /* ... */ try process.run() 3. Parent Process (Swift) Launch The parent process is the main Swift wrapper application, AthenaSentry.app (Bundle ID com.athena.AthenaSentry). It is
Oct ’25
Reply to Thread safety of os_activity_t
Thank you! You raise a good point with regard to scoping an activity across suspension points. os_activity_scope_{enter,leave} likely requires being called on the same thread even if the activity is automatically propagated across threads inside the scope. For non-detached Tasks this is simple as I can scope/apply the activity around the synchronous creation of the Task and the activity will be carried into the task automatically. Inside an async context I would probably need to ensure that I'm entering and leaving the scope on the same thread and even then it would likely break if that thread is used to run other work in the meantime. Hopefully we get Swift-native and Swift Concurrency compatible support for creating OS activities at some point, because they already work very well once created. They are even correctly propagated across custom non-GCD based TaskExecutors from what I can see. Restricting my use to non-detached Tasks is fine for now though, they are much more frequent than detached ones anyway.
Topic: App & System Services SubTopic: Core OS Tags:
Oct ’25
Thread safety of os_activity_t
Is it allowed to use an os_activity_t instance created with os_activity_create from multiple threads? In particular, would it be allowed to use os_activity_apply/os_activity_scope concurrently from multiple threads to associate separate chunks of work with the same activity? My use case is an activity where I'm using Task.detached to create a detached unstructured Task, which (as can be expected) prevents inheritance of the current activity. The bulk of the activity happens in the detached Task so I can just create the activity there but ideally I would like to also associate some of the setup work before spawning the Task with the same activity. So I'm wondering if it is safe to create the activity, apply it to the setup including spawning the detached Task and then capture and apply the same activity inside the Task as well where it might be applied concurrently with the first use on the thread spawning the Task.
4
0
189
Oct ’25
SwiftData: Crash when deleting from model, but only in prod
I'm testing my app before releasing to testers, and my app (both macOS and iOS) is crashing when I perform one operation, but only in the production build. I have data that loads from a remote source, and can be periodically updated. There is an option to delete all of that data from the iCloud data store, unless the user has modified a record. Each table has a flag to indicate that (userEdited). Here's the function that is crashing: func deleteCommonData(_ type: T.Type) throws { try modelContext.delete(model: T.self, where: #Predicate { !$0.userEdited }) } Here's one of the calls that results in a crash: try modelManager.deleteCommonData(Link.self) Here's the error from iOS Console: SwiftData/DataUtilities.swift:85: Fatal error: Couldn't find Link. on Link with fields [SwiftData.Schema.PropertyMetadata(name: id, keypath: Link., defaultValue: Optional(54EC6602-CA7C-4EC7-AC06-16E7F2E22DE7), metadata: nil), SwiftData.Schema.PropertyMetadata(name: name, keypath: Link., defaultValue: Optional(), metadata
3
0
136
Oct ’25
Reply to Correct SwiftData Concurrency Logic for UI and Extensions
When using SwiftData, I typically consider the following pattern: Start with accessing the data store from the main actor (MainActor) and with mainContext. Use @Query to gather data that will be rendered in a SwiftUI view. That way, the query controller under the hood observes changes on the data store, and updates the view, as discussed in this post. When you have a heavy task that should be done in a background queue, create a ModelActor with your app's shared model container, and do the task with the isolated modelContext. Use a Sendable data type to exchange data between the model actor (step 3) and the main actor. A SwiftData model is not Sendable, but the model's persistentModelID is, and so can be passed across actors. With this pattern, light tasks run in the main actor; heavy tasks run in a model actor and use Sendable types to exchange data across actors; @Query observes the changes on the data store and updates the UI. No race condition will happen. The only issue is that you may
Oct ’25
Correct SwiftData Concurrency Logic for UI and Extensions
Hi everyone, I'm looking for the correct architectural guidance for my SwiftData implementation. In my Swift project, I have dedicated async functions for adding, editing, and deleting each of my four models. I created these functions specifically to run certain logic whenever these operations occur. Since these functions are asynchronous, I call them from the UI (e.g., from a button press) by wrapping them in a Task. I've gone through three different approaches and am now stuck. Approach 1: @MainActor Functions Initially, my functions were marked with @MainActor and worked on the main ModelContext. This worked perfectly until I added support for App Intents and Widgets, which caused the app to crash with data race errors. Approach 2: Passing ModelContext as a Parameter To solve the crashes, I decided to have each function receive a ModelContext as a parameter. My SwiftUI views passed the main context (which they get from @Environment(.modelContext)), while the App Intents and Widgets created and pas
5
0
332
Oct ’25
Reply to BGContinuedProcessingTask what's the point?
So, let me start by jumping to the immediate point here: This initial sync is rare from a user perspective. Some may never have initial syncs that will take 2-3 minutes. Question is: 2-3 minutes outside the use case for this new feature? No, not at all. We can't guarantee any specific time, but there isn't any artificial throttle on timing and, theoretically, a task could run for an hour+ under the right circumstances. On an idle device as you're describing, 2-3 min. should have been fine. The next step here is to figure out what duet logged when we expired the task. Huh. How long does it take to expire once you enter the background? What does the > console log show (particularly from duet) when your task is expired? It can be a few minutes. I haven't timed it. OK. So the key here is that it's long enough that the processing task is keeping your app alive, at least some of the time. As background context, what's the work you're actually doing? I'm curious to why this would make a difference. It is running
Oct ’25
Swiftui Picker with optional value selected in picker
First the model: import SwiftData //Model one: type of contract, i.e. Firm Fixed Price, etc @Model final class TypeOfContract { var contracts: [Contract] @Attribute(.unique) var typeName: String @Attribute(.unique) var typeCode: String var typeDescription: String init(contracts: [Contract], typeName: String = , typeCode: String = , typeDescription: String = ) { self.contracts = contracts self.typeName = typeName self.typeCode = typeCode self.typeDescription = typeDescription } } //Model two: the Contract @Model final class Contract { var contractType: TypeOfContract? var costReports: [CostReport] @Attribute(.unique) var contractNumber: String @Attribute(.unique) var contractName: String var startDate: Date var endDate: Date var contractValue: Decimal var contractCompany: String var contractContact: String var contactEmail: String var contactPhone: String var contractNotes: String init(contractType: TypeOfContract?, costReports: [CostReport], contractNumber: String = , contractName: String = , startDa
2
0
236
Oct ’25
Reply to BGContinuedProcessingTask what's the point?
Huh. How long does it take to expire once you enter the background? What does the console log show (particularly from duet) when your task is expired? It can be a few minutes. I haven't time it. As background context, what's the work you're actually doing? I'm curious to why this would make a difference. It is running a long initial sync of data loading data into CoreData from a server. It almost always dies when trying to load relationships into CoreData. We are talking about 7000 plus relationship connections. How fast is that progress in real-world terms? A minute or two. How long does it take to process one item? A fraction of a second, I don't have exact times. How often are you updating progress? Many times a second. if you reduce the work such that you make rapid progress, both in terms of how long you take to complete and how frequently you report progress? I can't reduce how long it takes to update CoreData, On an initial sync, it's all or nothing; otherwise data will be corrupted.
Oct ’25
Reply to Picker using SwiftData
The selection parameter for the picker should be a single item and not an array @State private var contractType: TypeOfContract = // some default type also the type of the value passed to .tag() must be the same type as the property above. So this issue is not so much about SwiftData but instead understanding how a picker works.
Topic: UI Frameworks SubTopic: SwiftUI Tags:
Oct ’25
SwiftData and CloudKit Issues
Hi, I'm using SwiftData in my app, and I want to sent data to iCloud with CloudKit, but I found that If the user turns off my App iCloud sync function in the settings App, the local data will also be deleted. A better way is maintaining the local data, just don't connect to iCloud.How should I do that? I need guidance!!! I'm just getting started with CloudKit And I would be appreciated!
Replies
1
Boosts
0
Views
265
Activity
Nov ’25
SwiftData Migration: Objects Created in Custom Migration Aren't Persisted or Queryable (Repost)
I'm experiencing a critical issue with SwiftData custom migrations where objects created during migration appear to be inserted successfully but aren't persisted or found by queries after migration completes. The migration logs show objects being created, but subsequent queries return zero results. I'm migrating from schema version V2 to V2_5, which involves: Renaming Person class to GroupData Keeping the same data structure but changing the class name while keeping the old class. Using a custom migration stage to copy data from old to new schema Below is an extract of my two schema and migration plan: Environment: Xcode 16.0, iOS 18.0, Swift 6.0 SchemaV2 enum LinkMapV2: VersionedSchema { static let versionIdentifier: Schema.Version = .init(2, 0, 0) static var models: [any PersistentModel.Type] { [AnnotationData.self, Person.self, History.self] } @Model final class Person { @Attribute(.unique) var id: UUID var name: String var photo: String var requirement: String var statue: Bool var annotationId: U
Replies
1
Boosts
0
Views
323
Activity
Nov ’25
Reply to App crashed when switching between Annotation Tab and Group Tab with TabView init(selection:content:)
The reason actually is because SwiftData doesn't support using TabView .init(selection:content:) with .tabItem. Instead, use TabView .init(content:) with Tab.
Topic: UI Frameworks SubTopic: SwiftUI Tags:
Replies
Boosts
Views
Activity
Nov ’25
Reply to SwiftData error: NSKeyedUnarchiveFromData' should not be used to for un-archiving and will be removed in a future release
Bump. We need at least some guidance on this topic. Should we avoid codable structs in SwiftData models if trying to integrate with CloudKit? Maybe a flat structure for the data in the Models is the solution. But we have no idea
Replies
Boosts
Views
Activity
Nov ’25
SwiftData Migration: Objects Created in Custom Migration Aren't Persisted or Queryable
Description: I'm experiencing a critical issue with SwiftData custom migrations where objects created during migration appear to be inserted successfully but aren't persisted or found by queries after migration completes. The migration logs show objects being created, but subsequent queries return zero results. Problem Details: I'm migrating from schema version V2 to V3, which involves: Renaming Person class to GroupData Keeping the same data structure but changing the class name Using a custom migration stage to copy data from old to new schema Migration Code: swift static let migrationV2toV3 = MigrationStage.custom( fromVersion: LinkMapV2.self, toVersion: LinkMapV3.self, willMigrate: { context in do { let persons = try context.fetch(FetchDescriptor()) print(Found (persons.count) Person objects to migrate) // ✅ Shows 11 objects for person in persons { let newGroup = LinkMapV3.GroupData( id: person.id, // Same UUID name: person.name, // ... other properties ) context.insert(newGroup) print(Inserted G
Replies
1
Boosts
0
Views
112
Activity
Nov ’25
Reply to TCC Permission Inheritance Failure: Swift Parent -> Python Child
Hi, Thank you for the clarification request. You are correct in your assumption. 1. Daemon Clarification We are using the term daemon in the general sense of a persistent background helper process, not a system-wide launchd daemon (it is not registered in /Library/LaunchDaemons or managed by SMAppService). 2. Child Process (Python) Launch The Python process is launched directly as a child process of the main Swift application. As detailed in the Python Daemon Launch section of our document, we are using Swift's high-level Process API (which, as you noted, is layered on top of technologies like posix_spawn). The specific code used is: let process = Process() process.executableURL = URL(fileURLWithPath: pythonExecutablePath) // path is AthenaSentry.app/Contents/Helpers/AthenaSentry.app/Contents/MacOS/AthenaSentry process.environment = /* ... */ try process.run() 3. Parent Process (Swift) Launch The parent process is the main Swift wrapper application, AthenaSentry.app (Bundle ID com.athena.AthenaSentry). It is
Replies
Boosts
Views
Activity
Oct ’25
Reply to Thread safety of os_activity_t
Thank you! You raise a good point with regard to scoping an activity across suspension points. os_activity_scope_{enter,leave} likely requires being called on the same thread even if the activity is automatically propagated across threads inside the scope. For non-detached Tasks this is simple as I can scope/apply the activity around the synchronous creation of the Task and the activity will be carried into the task automatically. Inside an async context I would probably need to ensure that I'm entering and leaving the scope on the same thread and even then it would likely break if that thread is used to run other work in the meantime. Hopefully we get Swift-native and Swift Concurrency compatible support for creating OS activities at some point, because they already work very well once created. They are even correctly propagated across custom non-GCD based TaskExecutors from what I can see. Restricting my use to non-detached Tasks is fine for now though, they are much more frequent than detached ones anyway.
Topic: App & System Services SubTopic: Core OS Tags:
Replies
Boosts
Views
Activity
Oct ’25
Thread safety of os_activity_t
Is it allowed to use an os_activity_t instance created with os_activity_create from multiple threads? In particular, would it be allowed to use os_activity_apply/os_activity_scope concurrently from multiple threads to associate separate chunks of work with the same activity? My use case is an activity where I'm using Task.detached to create a detached unstructured Task, which (as can be expected) prevents inheritance of the current activity. The bulk of the activity happens in the detached Task so I can just create the activity there but ideally I would like to also associate some of the setup work before spawning the Task with the same activity. So I'm wondering if it is safe to create the activity, apply it to the setup including spawning the detached Task and then capture and apply the same activity inside the Task as well where it might be applied concurrently with the first use on the thread spawning the Task.
Replies
4
Boosts
0
Views
189
Activity
Oct ’25
SwiftData: Crash when deleting from model, but only in prod
I'm testing my app before releasing to testers, and my app (both macOS and iOS) is crashing when I perform one operation, but only in the production build. I have data that loads from a remote source, and can be periodically updated. There is an option to delete all of that data from the iCloud data store, unless the user has modified a record. Each table has a flag to indicate that (userEdited). Here's the function that is crashing: func deleteCommonData(_ type: T.Type) throws { try modelContext.delete(model: T.self, where: #Predicate { !$0.userEdited }) } Here's one of the calls that results in a crash: try modelManager.deleteCommonData(Link.self) Here's the error from iOS Console: SwiftData/DataUtilities.swift:85: Fatal error: Couldn't find Link. on Link with fields [SwiftData.Schema.PropertyMetadata(name: id, keypath: Link., defaultValue: Optional(54EC6602-CA7C-4EC7-AC06-16E7F2E22DE7), metadata: nil), SwiftData.Schema.PropertyMetadata(name: name, keypath: Link., defaultValue: Optional(), metadata
Replies
3
Boosts
0
Views
136
Activity
Oct ’25
Reply to Correct SwiftData Concurrency Logic for UI and Extensions
When using SwiftData, I typically consider the following pattern: Start with accessing the data store from the main actor (MainActor) and with mainContext. Use @Query to gather data that will be rendered in a SwiftUI view. That way, the query controller under the hood observes changes on the data store, and updates the view, as discussed in this post. When you have a heavy task that should be done in a background queue, create a ModelActor with your app's shared model container, and do the task with the isolated modelContext. Use a Sendable data type to exchange data between the model actor (step 3) and the main actor. A SwiftData model is not Sendable, but the model's persistentModelID is, and so can be passed across actors. With this pattern, light tasks run in the main actor; heavy tasks run in a model actor and use Sendable types to exchange data across actors; @Query observes the changes on the data store and updates the UI. No race condition will happen. The only issue is that you may
Replies
Boosts
Views
Activity
Oct ’25
Correct SwiftData Concurrency Logic for UI and Extensions
Hi everyone, I'm looking for the correct architectural guidance for my SwiftData implementation. In my Swift project, I have dedicated async functions for adding, editing, and deleting each of my four models. I created these functions specifically to run certain logic whenever these operations occur. Since these functions are asynchronous, I call them from the UI (e.g., from a button press) by wrapping them in a Task. I've gone through three different approaches and am now stuck. Approach 1: @MainActor Functions Initially, my functions were marked with @MainActor and worked on the main ModelContext. This worked perfectly until I added support for App Intents and Widgets, which caused the app to crash with data race errors. Approach 2: Passing ModelContext as a Parameter To solve the crashes, I decided to have each function receive a ModelContext as a parameter. My SwiftUI views passed the main context (which they get from @Environment(.modelContext)), while the App Intents and Widgets created and pas
Replies
5
Boosts
0
Views
332
Activity
Oct ’25
Reply to BGContinuedProcessingTask what's the point?
So, let me start by jumping to the immediate point here: This initial sync is rare from a user perspective. Some may never have initial syncs that will take 2-3 minutes. Question is: 2-3 minutes outside the use case for this new feature? No, not at all. We can't guarantee any specific time, but there isn't any artificial throttle on timing and, theoretically, a task could run for an hour+ under the right circumstances. On an idle device as you're describing, 2-3 min. should have been fine. The next step here is to figure out what duet logged when we expired the task. Huh. How long does it take to expire once you enter the background? What does the > console log show (particularly from duet) when your task is expired? It can be a few minutes. I haven't timed it. OK. So the key here is that it's long enough that the processing task is keeping your app alive, at least some of the time. As background context, what's the work you're actually doing? I'm curious to why this would make a difference. It is running
Replies
Boosts
Views
Activity
Oct ’25
Swiftui Picker with optional value selected in picker
First the model: import SwiftData //Model one: type of contract, i.e. Firm Fixed Price, etc @Model final class TypeOfContract { var contracts: [Contract] @Attribute(.unique) var typeName: String @Attribute(.unique) var typeCode: String var typeDescription: String init(contracts: [Contract], typeName: String = , typeCode: String = , typeDescription: String = ) { self.contracts = contracts self.typeName = typeName self.typeCode = typeCode self.typeDescription = typeDescription } } //Model two: the Contract @Model final class Contract { var contractType: TypeOfContract? var costReports: [CostReport] @Attribute(.unique) var contractNumber: String @Attribute(.unique) var contractName: String var startDate: Date var endDate: Date var contractValue: Decimal var contractCompany: String var contractContact: String var contactEmail: String var contactPhone: String var contractNotes: String init(contractType: TypeOfContract?, costReports: [CostReport], contractNumber: String = , contractName: String = , startDa
Replies
2
Boosts
0
Views
236
Activity
Oct ’25
Reply to BGContinuedProcessingTask what's the point?
Huh. How long does it take to expire once you enter the background? What does the console log show (particularly from duet) when your task is expired? It can be a few minutes. I haven't time it. As background context, what's the work you're actually doing? I'm curious to why this would make a difference. It is running a long initial sync of data loading data into CoreData from a server. It almost always dies when trying to load relationships into CoreData. We are talking about 7000 plus relationship connections. How fast is that progress in real-world terms? A minute or two. How long does it take to process one item? A fraction of a second, I don't have exact times. How often are you updating progress? Many times a second. if you reduce the work such that you make rapid progress, both in terms of how long you take to complete and how frequently you report progress? I can't reduce how long it takes to update CoreData, On an initial sync, it's all or nothing; otherwise data will be corrupted.
Replies
Boosts
Views
Activity
Oct ’25
Reply to Picker using SwiftData
The selection parameter for the picker should be a single item and not an array @State private var contractType: TypeOfContract = // some default type also the type of the value passed to .tag() must be the same type as the property above. So this issue is not so much about SwiftData but instead understanding how a picker works.
Topic: UI Frameworks SubTopic: SwiftUI Tags:
Replies
Boosts
Views
Activity
Oct ’25