SwiftData

RSS for tag

Learn to write model code declaratively to add managed persistence and efficient model fetching.

SwiftData Documentation

Posts under SwiftData subtopic

Post

Replies

Boosts

Views

Activity

Core Data apps no longer working after update to iOS27
I have two apps that both use Core Data. Since updating to XCode 27.1 and iOS 27 one works and one does not. Both apps have AppDelegates, SceneDelegates and CoreDataStacks that are the same, except for data entity names, etc. With App A, this works: extension StartViewController { func importJSONPlaceSeedDataIfNeeded() { let fetchRequest: NSFetchRequest<Places> = Places.fetchRequest() let count = try? coreDataStack.context.count(for: fetchRequest) guard let placeCount = count, placeCount == 0 else { return } importJSONPlaceData() } With App B, this does not work: extension StartViewController { func importBirdsJSONSeedDataIfNeeded() { let fetchRequest: NSFetchRequest<Birds> = Birds.fetchRequest() let count = try? coreDataStack.context.count(for: fetchRequest) guard let birdCount = count, birdCount == 0 else { return } importBirdsJSONData() } I get the error: Kafue_Birds/StartViewController.swift:77: Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value The line that throws the error is: let count = try? coreDataStack.context.count(for: fetchRequest) Any suggestions?
0
0
121
3d
SwiftData regression in iOS 27.2: inverse relationship not set on children when an uninserted model graph is attached to a persisted model
Since iOS 27.2 (24B119), SwiftData no longer sets the inverse (child → parent) relationship for the children of a model that hasn't been inserted yet when that model is attached to an already-saved model. The children are saved with a nil parent, so the parent's to-many relationship reads back empty. This happens in the same ModelContext and also after reopening the store. The same code works correctly on iOS 27.0 (24A5390f). @Model final class Ledger { @Relationship(deleteRule: .cascade, inverse: \Transaction.ledger) var transactions: [Transaction] = [] } @Model final class Transaction { var ledger: Ledger? @Relationship(deleteRule: .cascade, inverse: \Item.transaction) var items: [Item] = [] init(items: [Item]) { self.items = items } } @Model final class Item { var transaction: Transaction? } // Inside a @ModelActor; `ledger` is fetched and already saved. let transaction = Transaction(items: [Item(), Item()]) // not inserted ledger.transactions.append(transaction) // iOS 27.0: item.transaction === transaction for every item // iOS 27.2: item.transaction == nil for every item try modelContext.save() // iOS 27.2: transaction.items.count == 0 (expected 2); both items are orphaned rowsThe inverse is already nil before save(), so this isn't a save or flush problem. The link just isn't set when the graph is attached. Affected patterns on 27.2 • persisted.list.append(uninsertedParentWithChildren) • persisted.list[index] = uninsertedParentWithChildren • Reassigning persisted.list = [...] when the new models have their own child arrays (grandchildren end up orphaned) • Models with several to-many arrays of the same child type Not affected • A graph that's entirely new, including the root • To-one relationships set in init • Models inserted into the context before the relationship is set Toolchain ruled out. I built the repro on the same iPhone 13 (iOS 27.2) with three toolchains: xcode 26.6, 27.1 and 27.2 Workaround. Insert the children and set the inverse explicitly before saving: modelContext.insert(transaction) for item in transaction.items { modelContext.insert(item) item.transaction = transaction } ledger.transactions.append(transaction) try modelContext.save()You have to do this at every level, grandchildren included. Has anyone else seen this on 27.2? And can someone from the SwiftData team confirm whether this is an intended behavior change or a regression? Feedback: FB25355425 (includes a standalone repro project, reports from iOS 27.0 and 27.2, and a sysdiagnose)
0
0
225
3d
SwiftData and iCloud Backup — Protecting Sensitive Local Data
I'm developing SipBudget, an iPhone app that will store manually entered alcohol-consumption records locally using SwiftData. The app will not use CloudKit synchronization, HealthKit, or a developer-operated cloud database. I understand that App Review Guideline 5.1.3(ii) prohibits storing personal health information in iCloud. I would appreciate technical guidance on two questions: Can a local SwiftData database be reliably excluded from ordinary iCloud device backups? If so, what is Apple's recommended implementation for ensuring that the database and related files remain excluded, including after database updates or migrations? I'm asking before implementation so I can design the storage architecture correctly. Thank you.
1
0
141
6d
CoreData lightweight migration fails on iOS 26 only — "no such column: Z_110GROUPITEMS1"
We've spent several days diagnosing a CoreData migration crash that is iOS 26-specific and reproducible 100% of the time. Posting here in case others have hit this and because we believe it's an Apple bug worth documenting. Upgrading from our App Store build (CoreData model v10) to our latest TestFlight build (model v11) crashes on iOS 26 with: NSCocoaErrorDomain / Code 134110 no such column: "Z_110GROUPITEMS1" The same upgrade path on iOS 17 and iOS 18 works perfectly. What v10→v11 changes Two new entities added alphabetically early in the alphabet One new optional boolean attribute on an existing entity One new optional to-many relationship on the same existing entity All changes are lightweight-migration compatible. We use shouldMigrateStoreAutomatically = true and shouldInferMappingModelAutomatically = true Here's what we observed Adding two entities alphabetically shifts Z_ENT numbers for all subsequent entities. A central entity (EntityA) moves from Z_ENT 110 (v10) to Z_ENT 112 (v11). It has many-to-many relationships with four other entities (EntityB, EntityC, EntityD, EntityE), all using the same inverse relationship name: groupItems. Because multiple join tables reference EntityA via the same inverse name, CoreData appends a disambiguation suffix (1, 2, etc.) to column names in each join table. In v10, the relevant join tables are Z_110ENTITYB and Z_110ENTITYC, each with a column named Z_110GROUPITEMS + a suffix. -com.apple.CoreData.SQLDebug 3 prints: ALTER TABLE Z_112ENTITYB RENAME COLUMN Z_110GROUPITEMS1 TO Z_112GROUPITEMS1 But the actual column in a fresh iOS 26 v10 store is Z_110GROUPITEMS2. Column not found → crash. iOS 17/18 is consistent: both code paths use suffix 1 for Z_110ENTITYB and 2 for Z_110ENTITYC. Migration succeeds. To confirm We opened the SQLite store from a fresh iOS 26 v10 install and inspected the schema: CREATE TABLE Z_110ENTITYB ( Z_110GROUPITEMS2 INTEGER, Z_112ENTITYB INTEGER, PRIMARY KEY (Z_110GROUPITEMS2, Z_112ENTITYB) ); Then we manually renamed Z_110GROUPITEMS2 → Z_110GROUPITEMS1 and Z_110ENTITYC.Z_110GROUPITEMS1 → Z_110GROUPITEMS2 in the SQLite file. Re-ran the app — migration succeeded. The suffixes are literally swapped between what iOS 26 creates on fresh install vs. what iOS 26's migration engine expects. Our database has over 50 entities and we never before faced such an issue. This is not the first lightweight migration we are releasing after iOS 26 and that's what puzzled us. Why now?
5
0
1.1k
1w
modelContainer in SwiftData
Hello, In SwiftUI within Swift Playgrounds on iPad, I get two different results depending on whether I place .modelContainer(for: Valeur.self) immediately after ContentView() or after WindowGroup {....}. If I place it after WindowGroup {....}, I can neither save to nor query the database in the preview; it only works in read-only mode. If I place it after ContentView(), it works correctly in both preview and read-write mode. Which version should I use? Thanks for your feedback.
3
0
282
1w
SwiftData Model object added to multiple parent objects moves ownership to only last parent
I thought an object could be added to as many other parents as I wanted, but now it's not behaving. @Model final class Genre { var name:String; init(name:String) { self.name = name; } } @Model final class Disc { var genre:Array<Genre> = []; }Then elsewhere I made sure the user is not creating a duplicate Genre before adding either the existing one or a new one: struct BlahView: View { @Query var allGenres:[Genre]; var theseGenres; // Pretend this is actually assigned. var body: some View { if let idx = allGenres.firstIndex(where: { genr in genr.name == editStr; }) { theseGenres.append(allGenres[idx]); } else { theseGenres.append(Genre(name:editStr)); } } }When the genre gets added to the 2nd parent, it goes away in the 1st parent it was added to. I initially used the #Unique<Genre>([\.name]) thingy in Genre, but then read that it does not work when the data is stored in CloudKit, which I'm doing. Hence the check for existing I'm doing.
1
0
355
1w
SwiftData: "backing data was detached from a context without resolving attribute faults" when deleting a model shown in a @Query driven list
A dashboard screen lists cameras from a @Query. Each row is a child view that holds the model instance: @Query(filter: #Predicate { $0.device?.isSelected == true }) private var cameras: [CameraModel] List { ForEach(cameras) { camera in CameraCellView(camera: camera) //holds let camera: CameraModel } } The row reads model attributes in its body (camera.name, camera.cameraType, camera.thumbnailData). It also has a 1-second timer that updates a "last snapshot" subtitle, so it redraws on its own. A settings screen is pushed on top of the dashboard in the same NavigationStack. It deletes a camera like this: camera.modelContext?.delete(camera) try? camera.modelContext?.save() Immediately after the delete, the app crashes in the dashboard row's body when it reads an attribute: Fatal error: This backing data was detached from a context without resolving attribute faults: PersistentIdentifier(...) - \CameraModel.cameraType This is not 100% reproducible. The whole error message is: Thread 1: Fatal error: This backing data was detached from a context without resolving attribute faults: PersistentIdentifier(id: SwiftData.PersistentIdentifier.ID(backing: SwiftData.PersistentIdentifier.PersistentIdentifierBacking.managedObjectID(0x8f8ff6c009fee652 x-coredata://65230C45-6F86-4B64-AEAB-6AAA9CB72D24/CameraModel/p16))) - \CameraModel.cameraType I understand this is due to a small gap where the SwiftUI view is rerendered before Query updates the view because of the deletion and the SwiftUI view points at a nonexistent SwiftData record. I'm just wondering what's a good way of avoiding that? SwiftData is used project-wide so this can potentially happen on nearly every view.
0
0
106
3w
Core Data Transformable attribute with IN %@ predicate returns empty results when array contains more than 100 items on iOS 27
I’m seeing what appears to be a Core Data regression on iOS 27 when using an IN %@ predicate with a Transformable attribute containing String values. Before iOS 27, the following predicate worked correctly regardless of the number of values in the array: [NSPredicate predicateWithFormat:@"field IN %@", valuesArray] On iOS 27, I get different results depending on the number of items in valuesArray: valuesArray.count <= 100 → works correctly and returns the expected objects. valuesArray.count > 100 → returns an empty result, even though matching objects exist in the Core Data database. Reproduction Create a Core Data entity with a Transformable attribute containing String values. Store objects with values in this attribute. Create an array containing matching values. Execute a fetch using: [NSPredicate predicateWithFormat:@"field IN %@", valuesArray] Test with 100 values and then with more than 100 values. The issue is consistently reproducible on iOS 27. Interestingly, I also tested manually transforming the values in the array to the same representation used by the Transformable attribute. When doing this, the predicate works correctly even with more than 100 values. This makes me suspect that iOS 27/Core Data may not correctly transform the values supplied to the IN predicate when the array contains more than 100 items. Has anyone else observed this behavior on iOS 27? Is there a known limitation or change in Core Data predicate handling for Transformable attributes in iOS 27? The same Core Data model and predicate worked correctly on previous iOS versions.
0
0
153
3w
Custom SwiftData DataStore
In the sample code below I am reading and writing ProductRecord model objects to PostgreSQL using a custom DataStore. However it is unclear to me how I can set this up such that I am able to also write other model object types to the same custom DataStore. Currently the ProductPostgresSnapshot is specific to the ProductRecord and the PostgresSwiftDataStore Snapshot refers to this ProductPostgresSnapshot. Any idea how I would change this to accommodate different model object types such as SupplierRecord ? Full console program shown below. Full console program
3
0
289
Oct ’26
Transferable protocol
The Transferable protocol is Apple’s modern, Swift-native way to allow data to be shared across your app or between different apps. It standardizes how objects are serialized (converted to exportable data) and deserialized (imported back into objects) during operations like drag and drop, copy/paste, and system sharing sheets. Here is a breakdown of how it works and its core concepts: 1. Basic Requirements To make a custom type conform to Transferable, you implement a single static property called transferRepresentation. This property defines the rules for how your data is converted depending on how it is stored or shared. 2. Types of Transfer Representations Depending on your model's underlying structure, Core Transferable provides built-in representation wrappers: CodableRepresentation: Best for custom data models that already conform to Swift’s Codable protocol. It handles JSON/property-list encoding and decoding automatically. DataRepresentation: Best for raw data blobs held in memory (e.g., custom byte buffers or image data). FileRepresentation: Best for large files or assets on disk (e.g., videos, PDFs) so they can be streamed directly from a file path rather than loaded entirely into RAM. You can also use a TransferRepresentationBuilder to chain multiple representations together, declaring fallback formats in order of preference. 3. Proxy Representations If your model object doesn't need its own direct serialization format, you can use a ProxyRepresentation. This converts your custom object into another type that is already transferable (e.g., exporting a complex Document model as a plain String or URL). 4. SwiftUI Integration SwiftUI natively supports Transferable types, simplifying UI interaction features: Drag and Drop: Views can easily act as drag sources using modifiers like draggable(_:) or drop destinations using dropDestination(for:action:). Built-in Support: Common Swift and Apple framework types like String, URL, Data, and Image already conform to Transferable out of the box, making standard sharing seamless.
0
0
142
Oct ’26
[SwiftData]Is it safe to reference previous VersionedSchema types in a newer schema's models array?
I'm building a SwiftData migration strategy and want to confirm whether it's officially supported to reference types from a previous VersionedSchema in a newer version's models array. Setup V1 defines all 28 models under its own namespace: static let versionIdentifier = Schema.Version(1, 0, 0) static let models: [any PersistentModel.Type] = [ Self.ItemModel.self, Self.UserModel.self, // ... 28 models ] } When migrating to V2, only ItemModel changes. To avoid copying unchanged model definitions into every new schema version, I include the previous version's types directly in V2's models array: static let versionIdentifier = Schema.Version(2, 0, 0) static let models: [any PersistentModel.Type] = [ Self.ItemModel.self, // V2 type (changed) ApplicationDatabaseSchema_V1_0_0.UserModel.self, // V1 type (unchanged) // ... other unchanged models referencing V1 types ] } extension ApplicationDatabaseSchema_V2_0_0 { @Model final class ItemModel { /* updated definition */ } } Questions Since SwiftData uses the simple class name (not the fully-qualified name including namespace) as the entity name, this appears to work in basic testing. But is mixing types from different schema version namespaces in a single models array officially supported, especially when models have relationships across versions? How does SwiftData handle inverse relationships when a newly defined V2 model references an unchanged V1 model? Is there a risk of schema corruption, runtime crashes during migration, or breaking changes in future SwiftData/iOS updates? The alternative — duplicating all 28 model class definitions in every schema version — introduces significant maintenance overhead. What is the recommended pattern for handling unchanged models with relationships when migrating using VersionedSchema? The alternative — duplicating all 28 model class definitions in every schema version — introduces significant maintenance overhead. Is there a recommended pattern for handling unchanged models when migrating with VersionedSchema?
1
0
188
Sep ’26
SwiftData predicate with optional chaining failing on OS 27
The following predicate (which returns results on OS 26) only returns results on OS 27 when I comment out the last line: reviewDescriptor = FetchDescriptor<Flashcard>( predicate: #Predicate { $0.sourceLanguageRaw == rawLang && $0.cardStateRaw == reviewRaw && $0.dueDate < currentDate && !$0.isSuspended && advancedStudyEnabled.evaluate($0) && !($0.promotionLog?.isProcessing ?? false) // <- here }, sortBy: [SortDescriptor(\.previousInterval)] ) // where Flashcard — PromotionLog is a one-to-one optional relationship Because I’m still getting results on OS 26 from the same data, my guess is the line with optional chaining somehow causes the entire predicate to fail silently, without crashing the app. But I also don’t see any posts about it, so maybe it’s something I’m doing wrong? Is anyone else experiencing this? Any workarounds? ETA: However, this chaining appears to be working just fine: reviewDescriptor.predicate = #Predicate<Flashcard> { $0.sourceLanguageRaw == rawLang && $0.cardStateRaw == reviewRaw && ($0.pronunciationLog?.dueDate ?? currentDate) < currentDate && $0.pronunciationLog?.practiceStateRaw != masteredRaw && !$0.isSuspended } So I’m a bit lost. Maybe the syntax of the first? Something about using it alongside .evaluate()? ETA2: After a bit more debugging, when && !($0.promotionLog?.isProcessing ?? false) is commented out, a Flashcard where promotionLog == nil shows up. But if promotionLog == nil, the line should evaluate to !(false), i.e. true. So why would that line stop the card from showing up in the first place?
1
0
288
Sep ’26
HistoryObserver eventCounter updating 9-16 times per app launch because of CloudKit syncing?
I created a finance tracking app. I wanted to use HistoryObserver to determine when Transactions are created/updated/deleted on another device with the same appleId, so I can update some charts I have an @Observable model that has this (simplified) setup: private(set) var transactionObserver: HistoryObserver? func setupHistoryObserver(modelContainer: ModelContainer) throws { transactionObserver = try HistoryObserver( observedModels: [Transaction.self], modelContainer: modelContainer, ) } var transactionUpdateTrigger: Int { transactionObserver?.eventCounter ?? 0 } I have the view setup with: .task(id: viewModel.transactionUpdateTrigger) { print("updating chart data: \(viewModel.transactionUpdateTrigger)") await updateChartData() } When I launch my app on my iPhone, I see: updating chart data: 0 updating chart data: 1 updating chart data: 2 updating chart data: 3 updating chart data: 4 updating chart data: 5 updating chart data: 6 updating chart data: 7 updating chart data: 8 updating chart data: 9 updating chart data: 10 On simulator, it only fires once: updating chart data: 0 The docs state: "When relevant changes are detected, the observer updates its eventCounter property." The happens every single time I try deploying my app to my iPhone on iOS 27 beta 8, but with varying numbers of eventCounter increments. I only have the app installed on a single device with my Apple Account. Why is this happening? There should be no changes to my models, as is clear because there's no issues when running this in simulator.
2
0
621
Sep ’26
#Predicate needs better validation
Hi, Overview I am finding #Predicate to be a bit tricky when used with Swift Data It compiles fine but crashes at runtime I know the fix for the problem just wondering if such pitfalls can be avoided at compile time Exception *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'can't use NULL on left hand side' terminating due to uncaught exception of type NSException CoreData: error: SQLCore dispatchRequest: exception handling request: <NSSQLFetchRequestContext: 0x11209b000> , can't use NULL on left hand side with userInfo of (null) Questions Could anything be done to improve the safety to avoid such issues at runtime? Could I write the code better (better than the fix below) to avoid this? My thoughts Fix is possible however it wasn't obvious to me that there was a problem with my original code Would be nice to prevent them at compile time if possible. Currently got to be really careful to avoid such crashes. Code import Foundation import SwiftData @Model class Car { var name: String var modelRawValue: String? init(name: String, modelRawValue: String?) { self.name = name self.modelRawValue = modelRawValue } } enum CarModel: String, CaseIterable { case modelA case modelB } func makePredicate(filterModels: [CarModel]?) -> Predicate<Car> { let filterRawValues = filterModels?.map { $0.rawValue } let predicate = #Predicate<Car> { car in if let filterRawValues { if let carModelRawValue = car.modelRawValue { filterRawValues.contains(carModelRawValue) } else { false } } else { true } } return predicate } func fetch(context: ModelContext) throws { let predicate = makePredicate(filterModels: nil) let fetchDescriptor = FetchDescriptor(predicate: predicate) do { let cars = try context.fetch(fetchDescriptor) print(cars.count) } catch { print("Error: \(error)") throw error } } Fix func makePredicate(filterModels: [CarModel]?) -> Predicate<Car> { // Checking nil condition even before creating the predicate fixes the issue guard let filterModels else { return .true } let filterRawValues = filterModels.map { $0.rawValue } let predicate = #Predicate<Car> { car in if let carModelRawValue = car.modelRawValue { filterRawValues.contains(carModelRawValue) } else { false } } return predicate }
3
0
708
Sep ’26
Migrating a Transformable attribute from CoreData to SwiftData
I am migrating a CloudKit-synchronized multi-platform app from CoreData to SwiftData. (Xcode 27.0 beta 5). One of my Models/Entities contains a Transformable attribute, which is defined in the CoreData model editor as: and which is defined in the generated CoreData class as @NSManaged nonisolated public var authorNames: [String]? Using the built-in translation took, Xcode created a Model wich included @Attribute(.transformable(by: "NSSecureUnarchiveFromDataTransformerName")) var authorNames: [String] = [] This compiles but does not run. In the function func getModelContainer() throws -> ModelContainer { let storeURL = try FileManager.default.url( for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: true) .appendingPathComponent(dbName) let modelConfiguration = ModelConfiguration( schema: dbSchema, url: storeURL, cloudKitDatabase: .automatic) let container = try ModelContainer( for: dbSchema, migrationPlan: MigrationPlan.self, configurations: [modelConfiguration]) return container } the app throws a fatal error in the ModelContainer initializer, SwiftData/SchemaCoreData.swift:398: Fatal error: Application must register a ValueTransformer for NSSecureUnarchiveFromDataTransformerName So I added the following line of code at the top of this function: ValueTransformer.setValueTransformer( NSSecureUnarchiveFromDataTransformer(), forName: .secureUnarchiveFromDataTransformerName) which also compiles but also throws the same fatal error in the same place. Can anyone suggest how to resolve this problem? This is a CloudKit synchronized app, so I am constrained in what I can do with this attribute.
1
0
310
Aug ’26
How do I write this #Predicate?
I have two Models which are defined (simplified) as follows: @Model final class Book { var id: UUID = UUID() var title: String = "" var authors: [Author]? = [] } @Model final class Author { var id: UUID = UUID() var name: String "" @Relationship(inverse: \Book.authors) var books: [Book]? = [] } Both Book.authors and Author.books are defined as optionals to satisfy the requirements of CloudKit, although it is clear from the above that neither is ever actually nil. I am trying to write a #Predicate that finds objects of type Book with a title that matches a specified title and with an author that matches a specified author. The function I'd like to write looks something like this: func find(title: String, author: Author, with context: ModelContext) -> Book? { let same = ComparisonResult.orderedSame let predicate = #Predicate<Book> { book in book.title.caseInsensitiveCompare(title) == same && book.authors!.contains(where: { $0.id == author.id }) } let descriptor = FetchDescriptor<Book>(predicate: predicate) return try? context.fetch(descriptor).first } This function fails to compile inside the expansion of the #Predicate macro with a very long error message: Cannot convert value of type (a long 'PredicateExpresions....') (aka (another log 'PredicateExpressions....')) to closure result type 'any StandardPredicateExpression<Bool>' I don't understand. How can I write this predicate so that it will both compile and work? I know how to work around this problem, but would like to both deepen my understanding of Swift and SwiftData and to avoid the (inelegant) workaround.
2
0
507
Aug ’26
Sandboxed macOS app using SwiftData and CloudKit cannot initialize CloudKit mirroring.
I have a Mac and iOS app intended to sync data in iCloud. Both apps in TestFlight, the iOS reads and writes to iCloud but the Mac fails as the App Sandbox denies mach-lookup com.apple.cloudd, so NSCloudKitMirroringDelegate` never reaches the daemon and setup fails permanently. I have a minimal app reproducing the issue on for the Mac app. I also submitted a feedback FB24450529
1
0
762
Aug ’26
CoreDate->SwiftData Migration & CloudKit
I have an existing CoreData + CloudKit app which I would like to migrate to SwiftData + CloudKit. In the existing CoreData implementation, I have many optional fields (most of which have default values). I want to migrated them to SwiftData non-optional fields with default values. Can someone please confirm that I can do this without causing issues for my existing (CoreData + CloudKit) customers? I.e., I know I can do the migration on the local copy of the database, but I am worried about the CloudKit interaction. Specifically, I'm concerned about properties such as var title: String? which is implemented in CloudKit as CD_title CD_title_ckAsset Can I safely implement this in SwiftData as var title: String = "" without causing a problem with the CloudKit implementation?
1
0
836
Aug ’26
PersistentModel Sendable?
Most documentation on the web indicates that SwiftData Model instances are not Sendable. However, the current Xcode (Version 27.0 beta 5 (27A5237l)) indicates that @Model is Sendable. Is this a new feature in 2027 or is it an error in the documentation? @attached(member, conformances: Observable, PersistentModel, Sendable, names: named($backingData), named(persistentBackingData), named(schemaMetadata), named(init), named($observationRegistrar), named(_SwiftDataNoType), named(access), named(withMutation)) @attached(memberAttribute) @attached(extension, conformances: Observable, PersistentModel, Sendable) macro Model() I noticed this in the Quick Help as I was about to quit and go to bed. I'll check on this thread again after I wake up. If no answers I'll try writing a test case.
1
0
421
Aug ’26
Core Data apps no longer working after update to iOS27
I have two apps that both use Core Data. Since updating to XCode 27.1 and iOS 27 one works and one does not. Both apps have AppDelegates, SceneDelegates and CoreDataStacks that are the same, except for data entity names, etc. With App A, this works: extension StartViewController { func importJSONPlaceSeedDataIfNeeded() { let fetchRequest: NSFetchRequest<Places> = Places.fetchRequest() let count = try? coreDataStack.context.count(for: fetchRequest) guard let placeCount = count, placeCount == 0 else { return } importJSONPlaceData() } With App B, this does not work: extension StartViewController { func importBirdsJSONSeedDataIfNeeded() { let fetchRequest: NSFetchRequest<Birds> = Birds.fetchRequest() let count = try? coreDataStack.context.count(for: fetchRequest) guard let birdCount = count, birdCount == 0 else { return } importBirdsJSONData() } I get the error: Kafue_Birds/StartViewController.swift:77: Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value The line that throws the error is: let count = try? coreDataStack.context.count(for: fetchRequest) Any suggestions?
Replies
0
Boosts
0
Views
121
Activity
3d
SwiftData regression in iOS 27.2: inverse relationship not set on children when an uninserted model graph is attached to a persisted model
Since iOS 27.2 (24B119), SwiftData no longer sets the inverse (child → parent) relationship for the children of a model that hasn't been inserted yet when that model is attached to an already-saved model. The children are saved with a nil parent, so the parent's to-many relationship reads back empty. This happens in the same ModelContext and also after reopening the store. The same code works correctly on iOS 27.0 (24A5390f). @Model final class Ledger { @Relationship(deleteRule: .cascade, inverse: \Transaction.ledger) var transactions: [Transaction] = [] } @Model final class Transaction { var ledger: Ledger? @Relationship(deleteRule: .cascade, inverse: \Item.transaction) var items: [Item] = [] init(items: [Item]) { self.items = items } } @Model final class Item { var transaction: Transaction? } // Inside a @ModelActor; `ledger` is fetched and already saved. let transaction = Transaction(items: [Item(), Item()]) // not inserted ledger.transactions.append(transaction) // iOS 27.0: item.transaction === transaction for every item // iOS 27.2: item.transaction == nil for every item try modelContext.save() // iOS 27.2: transaction.items.count == 0 (expected 2); both items are orphaned rowsThe inverse is already nil before save(), so this isn't a save or flush problem. The link just isn't set when the graph is attached. Affected patterns on 27.2 • persisted.list.append(uninsertedParentWithChildren) • persisted.list[index] = uninsertedParentWithChildren • Reassigning persisted.list = [...] when the new models have their own child arrays (grandchildren end up orphaned) • Models with several to-many arrays of the same child type Not affected • A graph that's entirely new, including the root • To-one relationships set in init • Models inserted into the context before the relationship is set Toolchain ruled out. I built the repro on the same iPhone 13 (iOS 27.2) with three toolchains: xcode 26.6, 27.1 and 27.2 Workaround. Insert the children and set the inverse explicitly before saving: modelContext.insert(transaction) for item in transaction.items { modelContext.insert(item) item.transaction = transaction } ledger.transactions.append(transaction) try modelContext.save()You have to do this at every level, grandchildren included. Has anyone else seen this on 27.2? And can someone from the SwiftData team confirm whether this is an intended behavior change or a regression? Feedback: FB25355425 (includes a standalone repro project, reports from iOS 27.0 and 27.2, and a sysdiagnose)
Replies
0
Boosts
0
Views
225
Activity
3d
SwiftData and iCloud Backup — Protecting Sensitive Local Data
I'm developing SipBudget, an iPhone app that will store manually entered alcohol-consumption records locally using SwiftData. The app will not use CloudKit synchronization, HealthKit, or a developer-operated cloud database. I understand that App Review Guideline 5.1.3(ii) prohibits storing personal health information in iCloud. I would appreciate technical guidance on two questions: Can a local SwiftData database be reliably excluded from ordinary iCloud device backups? If so, what is Apple's recommended implementation for ensuring that the database and related files remain excluded, including after database updates or migrations? I'm asking before implementation so I can design the storage architecture correctly. Thank you.
Replies
1
Boosts
0
Views
141
Activity
6d
CoreData lightweight migration fails on iOS 26 only — "no such column: Z_110GROUPITEMS1"
We've spent several days diagnosing a CoreData migration crash that is iOS 26-specific and reproducible 100% of the time. Posting here in case others have hit this and because we believe it's an Apple bug worth documenting. Upgrading from our App Store build (CoreData model v10) to our latest TestFlight build (model v11) crashes on iOS 26 with: NSCocoaErrorDomain / Code 134110 no such column: "Z_110GROUPITEMS1" The same upgrade path on iOS 17 and iOS 18 works perfectly. What v10→v11 changes Two new entities added alphabetically early in the alphabet One new optional boolean attribute on an existing entity One new optional to-many relationship on the same existing entity All changes are lightweight-migration compatible. We use shouldMigrateStoreAutomatically = true and shouldInferMappingModelAutomatically = true Here's what we observed Adding two entities alphabetically shifts Z_ENT numbers for all subsequent entities. A central entity (EntityA) moves from Z_ENT 110 (v10) to Z_ENT 112 (v11). It has many-to-many relationships with four other entities (EntityB, EntityC, EntityD, EntityE), all using the same inverse relationship name: groupItems. Because multiple join tables reference EntityA via the same inverse name, CoreData appends a disambiguation suffix (1, 2, etc.) to column names in each join table. In v10, the relevant join tables are Z_110ENTITYB and Z_110ENTITYC, each with a column named Z_110GROUPITEMS + a suffix. -com.apple.CoreData.SQLDebug 3 prints: ALTER TABLE Z_112ENTITYB RENAME COLUMN Z_110GROUPITEMS1 TO Z_112GROUPITEMS1 But the actual column in a fresh iOS 26 v10 store is Z_110GROUPITEMS2. Column not found → crash. iOS 17/18 is consistent: both code paths use suffix 1 for Z_110ENTITYB and 2 for Z_110ENTITYC. Migration succeeds. To confirm We opened the SQLite store from a fresh iOS 26 v10 install and inspected the schema: CREATE TABLE Z_110ENTITYB ( Z_110GROUPITEMS2 INTEGER, Z_112ENTITYB INTEGER, PRIMARY KEY (Z_110GROUPITEMS2, Z_112ENTITYB) ); Then we manually renamed Z_110GROUPITEMS2 → Z_110GROUPITEMS1 and Z_110ENTITYC.Z_110GROUPITEMS1 → Z_110GROUPITEMS2 in the SQLite file. Re-ran the app — migration succeeded. The suffixes are literally swapped between what iOS 26 creates on fresh install vs. what iOS 26's migration engine expects. Our database has over 50 entities and we never before faced such an issue. This is not the first lightweight migration we are releasing after iOS 26 and that's what puzzled us. Why now?
Replies
5
Boosts
0
Views
1.1k
Activity
1w
modelContainer in SwiftData
Hello, In SwiftUI within Swift Playgrounds on iPad, I get two different results depending on whether I place .modelContainer(for: Valeur.self) immediately after ContentView() or after WindowGroup {....}. If I place it after WindowGroup {....}, I can neither save to nor query the database in the preview; it only works in read-only mode. If I place it after ContentView(), it works correctly in both preview and read-write mode. Which version should I use? Thanks for your feedback.
Replies
3
Boosts
0
Views
282
Activity
1w
SwiftData Model object added to multiple parent objects moves ownership to only last parent
I thought an object could be added to as many other parents as I wanted, but now it's not behaving. @Model final class Genre { var name:String; init(name:String) { self.name = name; } } @Model final class Disc { var genre:Array<Genre> = []; }Then elsewhere I made sure the user is not creating a duplicate Genre before adding either the existing one or a new one: struct BlahView: View { @Query var allGenres:[Genre]; var theseGenres; // Pretend this is actually assigned. var body: some View { if let idx = allGenres.firstIndex(where: { genr in genr.name == editStr; }) { theseGenres.append(allGenres[idx]); } else { theseGenres.append(Genre(name:editStr)); } } }When the genre gets added to the 2nd parent, it goes away in the 1st parent it was added to. I initially used the #Unique<Genre>([\.name]) thingy in Genre, but then read that it does not work when the data is stored in CloudKit, which I'm doing. Hence the check for existing I'm doing.
Replies
1
Boosts
0
Views
355
Activity
1w
SwiftData: "backing data was detached from a context without resolving attribute faults" when deleting a model shown in a @Query driven list
A dashboard screen lists cameras from a @Query. Each row is a child view that holds the model instance: @Query(filter: #Predicate { $0.device?.isSelected == true }) private var cameras: [CameraModel] List { ForEach(cameras) { camera in CameraCellView(camera: camera) //holds let camera: CameraModel } } The row reads model attributes in its body (camera.name, camera.cameraType, camera.thumbnailData). It also has a 1-second timer that updates a "last snapshot" subtitle, so it redraws on its own. A settings screen is pushed on top of the dashboard in the same NavigationStack. It deletes a camera like this: camera.modelContext?.delete(camera) try? camera.modelContext?.save() Immediately after the delete, the app crashes in the dashboard row's body when it reads an attribute: Fatal error: This backing data was detached from a context without resolving attribute faults: PersistentIdentifier(...) - \CameraModel.cameraType This is not 100% reproducible. The whole error message is: Thread 1: Fatal error: This backing data was detached from a context without resolving attribute faults: PersistentIdentifier(id: SwiftData.PersistentIdentifier.ID(backing: SwiftData.PersistentIdentifier.PersistentIdentifierBacking.managedObjectID(0x8f8ff6c009fee652 x-coredata://65230C45-6F86-4B64-AEAB-6AAA9CB72D24/CameraModel/p16))) - \CameraModel.cameraType I understand this is due to a small gap where the SwiftUI view is rerendered before Query updates the view because of the deletion and the SwiftUI view points at a nonexistent SwiftData record. I'm just wondering what's a good way of avoiding that? SwiftData is used project-wide so this can potentially happen on nearly every view.
Replies
0
Boosts
0
Views
106
Activity
3w
Core Data Transformable attribute with IN %@ predicate returns empty results when array contains more than 100 items on iOS 27
I’m seeing what appears to be a Core Data regression on iOS 27 when using an IN %@ predicate with a Transformable attribute containing String values. Before iOS 27, the following predicate worked correctly regardless of the number of values in the array: [NSPredicate predicateWithFormat:@"field IN %@", valuesArray] On iOS 27, I get different results depending on the number of items in valuesArray: valuesArray.count <= 100 → works correctly and returns the expected objects. valuesArray.count > 100 → returns an empty result, even though matching objects exist in the Core Data database. Reproduction Create a Core Data entity with a Transformable attribute containing String values. Store objects with values in this attribute. Create an array containing matching values. Execute a fetch using: [NSPredicate predicateWithFormat:@"field IN %@", valuesArray] Test with 100 values and then with more than 100 values. The issue is consistently reproducible on iOS 27. Interestingly, I also tested manually transforming the values in the array to the same representation used by the Transformable attribute. When doing this, the predicate works correctly even with more than 100 values. This makes me suspect that iOS 27/Core Data may not correctly transform the values supplied to the IN predicate when the array contains more than 100 items. Has anyone else observed this behavior on iOS 27? Is there a known limitation or change in Core Data predicate handling for Transformable attributes in iOS 27? The same Core Data model and predicate worked correctly on previous iOS versions.
Replies
0
Boosts
0
Views
153
Activity
3w
Custom SwiftData DataStore
In the sample code below I am reading and writing ProductRecord model objects to PostgreSQL using a custom DataStore. However it is unclear to me how I can set this up such that I am able to also write other model object types to the same custom DataStore. Currently the ProductPostgresSnapshot is specific to the ProductRecord and the PostgresSwiftDataStore Snapshot refers to this ProductPostgresSnapshot. Any idea how I would change this to accommodate different model object types such as SupplierRecord ? Full console program shown below. Full console program
Replies
3
Boosts
0
Views
289
Activity
Oct ’26
Transferable protocol
The Transferable protocol is Apple’s modern, Swift-native way to allow data to be shared across your app or between different apps. It standardizes how objects are serialized (converted to exportable data) and deserialized (imported back into objects) during operations like drag and drop, copy/paste, and system sharing sheets. Here is a breakdown of how it works and its core concepts: 1. Basic Requirements To make a custom type conform to Transferable, you implement a single static property called transferRepresentation. This property defines the rules for how your data is converted depending on how it is stored or shared. 2. Types of Transfer Representations Depending on your model's underlying structure, Core Transferable provides built-in representation wrappers: CodableRepresentation: Best for custom data models that already conform to Swift’s Codable protocol. It handles JSON/property-list encoding and decoding automatically. DataRepresentation: Best for raw data blobs held in memory (e.g., custom byte buffers or image data). FileRepresentation: Best for large files or assets on disk (e.g., videos, PDFs) so they can be streamed directly from a file path rather than loaded entirely into RAM. You can also use a TransferRepresentationBuilder to chain multiple representations together, declaring fallback formats in order of preference. 3. Proxy Representations If your model object doesn't need its own direct serialization format, you can use a ProxyRepresentation. This converts your custom object into another type that is already transferable (e.g., exporting a complex Document model as a plain String or URL). 4. SwiftUI Integration SwiftUI natively supports Transferable types, simplifying UI interaction features: Drag and Drop: Views can easily act as drag sources using modifiers like draggable(_:) or drop destinations using dropDestination(for:action:). Built-in Support: Common Swift and Apple framework types like String, URL, Data, and Image already conform to Transferable out of the box, making standard sharing seamless.
Replies
0
Boosts
0
Views
142
Activity
Oct ’26
[SwiftData]Is it safe to reference previous VersionedSchema types in a newer schema's models array?
I'm building a SwiftData migration strategy and want to confirm whether it's officially supported to reference types from a previous VersionedSchema in a newer version's models array. Setup V1 defines all 28 models under its own namespace: static let versionIdentifier = Schema.Version(1, 0, 0) static let models: [any PersistentModel.Type] = [ Self.ItemModel.self, Self.UserModel.self, // ... 28 models ] } When migrating to V2, only ItemModel changes. To avoid copying unchanged model definitions into every new schema version, I include the previous version's types directly in V2's models array: static let versionIdentifier = Schema.Version(2, 0, 0) static let models: [any PersistentModel.Type] = [ Self.ItemModel.self, // V2 type (changed) ApplicationDatabaseSchema_V1_0_0.UserModel.self, // V1 type (unchanged) // ... other unchanged models referencing V1 types ] } extension ApplicationDatabaseSchema_V2_0_0 { @Model final class ItemModel { /* updated definition */ } } Questions Since SwiftData uses the simple class name (not the fully-qualified name including namespace) as the entity name, this appears to work in basic testing. But is mixing types from different schema version namespaces in a single models array officially supported, especially when models have relationships across versions? How does SwiftData handle inverse relationships when a newly defined V2 model references an unchanged V1 model? Is there a risk of schema corruption, runtime crashes during migration, or breaking changes in future SwiftData/iOS updates? The alternative — duplicating all 28 model class definitions in every schema version — introduces significant maintenance overhead. What is the recommended pattern for handling unchanged models with relationships when migrating using VersionedSchema? The alternative — duplicating all 28 model class definitions in every schema version — introduces significant maintenance overhead. Is there a recommended pattern for handling unchanged models when migrating with VersionedSchema?
Replies
1
Boosts
0
Views
188
Activity
Sep ’26
SwiftData predicate with optional chaining failing on OS 27
The following predicate (which returns results on OS 26) only returns results on OS 27 when I comment out the last line: reviewDescriptor = FetchDescriptor<Flashcard>( predicate: #Predicate { $0.sourceLanguageRaw == rawLang && $0.cardStateRaw == reviewRaw && $0.dueDate < currentDate && !$0.isSuspended && advancedStudyEnabled.evaluate($0) && !($0.promotionLog?.isProcessing ?? false) // <- here }, sortBy: [SortDescriptor(\.previousInterval)] ) // where Flashcard — PromotionLog is a one-to-one optional relationship Because I’m still getting results on OS 26 from the same data, my guess is the line with optional chaining somehow causes the entire predicate to fail silently, without crashing the app. But I also don’t see any posts about it, so maybe it’s something I’m doing wrong? Is anyone else experiencing this? Any workarounds? ETA: However, this chaining appears to be working just fine: reviewDescriptor.predicate = #Predicate<Flashcard> { $0.sourceLanguageRaw == rawLang && $0.cardStateRaw == reviewRaw && ($0.pronunciationLog?.dueDate ?? currentDate) < currentDate && $0.pronunciationLog?.practiceStateRaw != masteredRaw && !$0.isSuspended } So I’m a bit lost. Maybe the syntax of the first? Something about using it alongside .evaluate()? ETA2: After a bit more debugging, when && !($0.promotionLog?.isProcessing ?? false) is commented out, a Flashcard where promotionLog == nil shows up. But if promotionLog == nil, the line should evaluate to !(false), i.e. true. So why would that line stop the card from showing up in the first place?
Replies
1
Boosts
0
Views
288
Activity
Sep ’26
HistoryObserver eventCounter updating 9-16 times per app launch because of CloudKit syncing?
I created a finance tracking app. I wanted to use HistoryObserver to determine when Transactions are created/updated/deleted on another device with the same appleId, so I can update some charts I have an @Observable model that has this (simplified) setup: private(set) var transactionObserver: HistoryObserver? func setupHistoryObserver(modelContainer: ModelContainer) throws { transactionObserver = try HistoryObserver( observedModels: [Transaction.self], modelContainer: modelContainer, ) } var transactionUpdateTrigger: Int { transactionObserver?.eventCounter ?? 0 } I have the view setup with: .task(id: viewModel.transactionUpdateTrigger) { print("updating chart data: \(viewModel.transactionUpdateTrigger)") await updateChartData() } When I launch my app on my iPhone, I see: updating chart data: 0 updating chart data: 1 updating chart data: 2 updating chart data: 3 updating chart data: 4 updating chart data: 5 updating chart data: 6 updating chart data: 7 updating chart data: 8 updating chart data: 9 updating chart data: 10 On simulator, it only fires once: updating chart data: 0 The docs state: "When relevant changes are detected, the observer updates its eventCounter property." The happens every single time I try deploying my app to my iPhone on iOS 27 beta 8, but with varying numbers of eventCounter increments. I only have the app installed on a single device with my Apple Account. Why is this happening? There should be no changes to my models, as is clear because there's no issues when running this in simulator.
Replies
2
Boosts
0
Views
621
Activity
Sep ’26
#Predicate needs better validation
Hi, Overview I am finding #Predicate to be a bit tricky when used with Swift Data It compiles fine but crashes at runtime I know the fix for the problem just wondering if such pitfalls can be avoided at compile time Exception *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'can't use NULL on left hand side' terminating due to uncaught exception of type NSException CoreData: error: SQLCore dispatchRequest: exception handling request: <NSSQLFetchRequestContext: 0x11209b000> , can't use NULL on left hand side with userInfo of (null) Questions Could anything be done to improve the safety to avoid such issues at runtime? Could I write the code better (better than the fix below) to avoid this? My thoughts Fix is possible however it wasn't obvious to me that there was a problem with my original code Would be nice to prevent them at compile time if possible. Currently got to be really careful to avoid such crashes. Code import Foundation import SwiftData @Model class Car { var name: String var modelRawValue: String? init(name: String, modelRawValue: String?) { self.name = name self.modelRawValue = modelRawValue } } enum CarModel: String, CaseIterable { case modelA case modelB } func makePredicate(filterModels: [CarModel]?) -> Predicate<Car> { let filterRawValues = filterModels?.map { $0.rawValue } let predicate = #Predicate<Car> { car in if let filterRawValues { if let carModelRawValue = car.modelRawValue { filterRawValues.contains(carModelRawValue) } else { false } } else { true } } return predicate } func fetch(context: ModelContext) throws { let predicate = makePredicate(filterModels: nil) let fetchDescriptor = FetchDescriptor(predicate: predicate) do { let cars = try context.fetch(fetchDescriptor) print(cars.count) } catch { print("Error: \(error)") throw error } } Fix func makePredicate(filterModels: [CarModel]?) -> Predicate<Car> { // Checking nil condition even before creating the predicate fixes the issue guard let filterModels else { return .true } let filterRawValues = filterModels.map { $0.rawValue } let predicate = #Predicate<Car> { car in if let carModelRawValue = car.modelRawValue { filterRawValues.contains(carModelRawValue) } else { false } } return predicate }
Replies
3
Boosts
0
Views
708
Activity
Sep ’26
Migrating a Transformable attribute from CoreData to SwiftData
I am migrating a CloudKit-synchronized multi-platform app from CoreData to SwiftData. (Xcode 27.0 beta 5). One of my Models/Entities contains a Transformable attribute, which is defined in the CoreData model editor as: and which is defined in the generated CoreData class as @NSManaged nonisolated public var authorNames: [String]? Using the built-in translation took, Xcode created a Model wich included @Attribute(.transformable(by: "NSSecureUnarchiveFromDataTransformerName")) var authorNames: [String] = [] This compiles but does not run. In the function func getModelContainer() throws -> ModelContainer { let storeURL = try FileManager.default.url( for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: true) .appendingPathComponent(dbName) let modelConfiguration = ModelConfiguration( schema: dbSchema, url: storeURL, cloudKitDatabase: .automatic) let container = try ModelContainer( for: dbSchema, migrationPlan: MigrationPlan.self, configurations: [modelConfiguration]) return container } the app throws a fatal error in the ModelContainer initializer, SwiftData/SchemaCoreData.swift:398: Fatal error: Application must register a ValueTransformer for NSSecureUnarchiveFromDataTransformerName So I added the following line of code at the top of this function: ValueTransformer.setValueTransformer( NSSecureUnarchiveFromDataTransformer(), forName: .secureUnarchiveFromDataTransformerName) which also compiles but also throws the same fatal error in the same place. Can anyone suggest how to resolve this problem? This is a CloudKit synchronized app, so I am constrained in what I can do with this attribute.
Replies
1
Boosts
0
Views
310
Activity
Aug ’26
How do I write this #Predicate?
I have two Models which are defined (simplified) as follows: @Model final class Book { var id: UUID = UUID() var title: String = "" var authors: [Author]? = [] } @Model final class Author { var id: UUID = UUID() var name: String "" @Relationship(inverse: \Book.authors) var books: [Book]? = [] } Both Book.authors and Author.books are defined as optionals to satisfy the requirements of CloudKit, although it is clear from the above that neither is ever actually nil. I am trying to write a #Predicate that finds objects of type Book with a title that matches a specified title and with an author that matches a specified author. The function I'd like to write looks something like this: func find(title: String, author: Author, with context: ModelContext) -> Book? { let same = ComparisonResult.orderedSame let predicate = #Predicate<Book> { book in book.title.caseInsensitiveCompare(title) == same && book.authors!.contains(where: { $0.id == author.id }) } let descriptor = FetchDescriptor<Book>(predicate: predicate) return try? context.fetch(descriptor).first } This function fails to compile inside the expansion of the #Predicate macro with a very long error message: Cannot convert value of type (a long 'PredicateExpresions....') (aka (another log 'PredicateExpressions....')) to closure result type 'any StandardPredicateExpression<Bool>' I don't understand. How can I write this predicate so that it will both compile and work? I know how to work around this problem, but would like to both deepen my understanding of Swift and SwiftData and to avoid the (inelegant) workaround.
Replies
2
Boosts
0
Views
507
Activity
Aug ’26
Sandboxed macOS app using SwiftData and CloudKit cannot initialize CloudKit mirroring.
I have a Mac and iOS app intended to sync data in iCloud. Both apps in TestFlight, the iOS reads and writes to iCloud but the Mac fails as the App Sandbox denies mach-lookup com.apple.cloudd, so NSCloudKitMirroringDelegate` never reaches the daemon and setup fails permanently. I have a minimal app reproducing the issue on for the Mac app. I also submitted a feedback FB24450529
Replies
1
Boosts
0
Views
762
Activity
Aug ’26
CoreDate->SwiftData Migration & CloudKit
I have an existing CoreData + CloudKit app which I would like to migrate to SwiftData + CloudKit. In the existing CoreData implementation, I have many optional fields (most of which have default values). I want to migrated them to SwiftData non-optional fields with default values. Can someone please confirm that I can do this without causing issues for my existing (CoreData + CloudKit) customers? I.e., I know I can do the migration on the local copy of the database, but I am worried about the CloudKit interaction. Specifically, I'm concerned about properties such as var title: String? which is implemented in CloudKit as CD_title CD_title_ckAsset Can I safely implement this in SwiftData as var title: String = "" without causing a problem with the CloudKit implementation?
Replies
1
Boosts
0
Views
836
Activity
Aug ’26
PersistentModel Sendable?
Most documentation on the web indicates that SwiftData Model instances are not Sendable. However, the current Xcode (Version 27.0 beta 5 (27A5237l)) indicates that @Model is Sendable. Is this a new feature in 2027 or is it an error in the documentation? @attached(member, conformances: Observable, PersistentModel, Sendable, names: named($backingData), named(persistentBackingData), named(schemaMetadata), named(init), named($observationRegistrar), named(_SwiftDataNoType), named(access), named(withMutation)) @attached(memberAttribute) @attached(extension, conformances: Observable, PersistentModel, Sendable) macro Model() I noticed this in the Quick Help as I was about to quit and go to bed. I'll check on this thread again after I wake up. If no answers I'll try writing a test case.
Replies
1
Boosts
0
Views
421
Activity
Aug ’26