Core Data

RSS for tag

Save your application’s permanent data for offline use, cache temporary data, and add undo functionality to your app on a single device using Core Data.

Posts under Core Data tag

128 Posts
Sort by:

Post

Replies

Boosts

Views

Activity

SQLite strftime() support with Core Data FetchRequest
My entity has a startDate (NSTime) attribute where I use the date and time in my detail display of the entity. And in my list, I need to group my entities by day (YYMMDD) based on the start date; and I want to ensure that it can adapt to the region where the user is currently (e.g. if user travels or migrate, the YYMMDD should be adapted based on the current region). Does Core Data SectionedFetchRequest supports strftime() functions from SQLite (https://sqlite.org/lang_datefunc.html) or what is an effective alternative sectioned fetch in my case?
0
0
313
1d
Core Data + CKSyncEngine with Swift 6 — concurrency, Sendable, and best practices validation
Hi everyone, I’ve been working on migrating my app (SwimTimes, which helps swimmers track their times) to use Core Data + CKSyncEngine with Swift 6. After many iterations, forum searches, and experimentation, I’ve created a focused sample project that demonstrates the architecture I’m using. The good news: 👉 I believe the crashes I was experiencing are now solved, and the sync behavior is working correctly. 👉 The demo project compiles and runs cleanly with Swift 6. However, before adopting this as the final architecture, I’d like to ask the community (and hopefully Apple engineers) to validate a few critical points, especially regarding Swift 6 concurrency and Core Data contexts. Architecture Overview Persistence layer: Persistence.swift sets up the Core Data stack with a main viewContext and a background context for CKSyncEngine. Repositories: All Core Data access is abstracted into repository classes (UsersRepository, SwimTimesRepository), with async/await methods. SyncEngine: Wraps CKSyncEngine, handles system fields, sync tokens, and bridging between Core Data entities and CloudKit records. ViewModels: Marked @MainActor, exposing @Published arrays for SwiftUI. They never touch Core Data directly, only via repositories. UI: Simple SwiftUI views bound to the ViewModels. Entities: UserEntity → represents swimmers. SwimTimeEntity → times linked to a user (1-to-many). Current Status The project works and syncs across devices. But there are two open concerns I’d like validated: Concurrency & Memory Safety Am I correctly separating viewContext (main/UI) vs. background context (used by CKSyncEngine)? Could there still be hidden risks of race conditions or memory crashes that I’m not catching? Swift 6 Sendable Compliance Currently, I still need @unchecked Sendable in the SyncEngine and repository layers. What is the recommended way to fully remove these workarounds and make the code safe under Swift 6’s stricter concurrency rules? Request Please review this sample project and confirm whether the concurrency model is correct. Suggest how I can remove the @unchecked Sendable annotations safely. Any additional code improvements or best practices would also be very welcome — the intention is to share this as a community resource. I believe once finalized, this could serve as a good reference demo for Core Data + CKSyncEngine + Swift 6, helping others migrate safely. Environment iOS 18.5 Xcode 16.4 macOS 15.6 Swift 6 Sample Project Here is the full sample project on GitHub: 👉 [https://github.com/jarnaez728/coredata-cksyncengine-swift6] Thanks a lot for your time and for any insights! Best regards, Javier Arnáez de Pedro
0
0
311
2d
Core Data initialization causes app to deadlock on startup
Users have been reporting that the TestFlight version of my app (compiled with Xcode 26 Beta 6 17A5305f) is sometimes crashing on startup. Upon investigating their ips files, it looks like Core Data is locking up internally during its initialization, resulting in iOS killing my app. I have not recently changed my Core Data initialization logic, and it's unclear how I should proceed. Is this a known issue? Any recommended workaround? I have attached the crash stack below. Thanks! crash_log.txt
2
0
54
1d
Xcode 26: Sendable checking + NSManagedObjectContext.perform in Swift 6
I have some code which handles doing some computation on a background thread before updating Core Data NSManagedObjects by using the NSManagedObjectContext.perform functions. This code is covered in Sendable warnings in Xcode 26 (beta 6) because my NSManagedObject subclasses (autogenerated) are non-Sendable and NSManagedObjectContext.perform function takes a Sendable closure. But I can't really figure out what I should be doing. I realize this pattern is non-ideal for Swift concurrency, but it's what Core Data demands AFAIK. How do I deal with this? let moc = object.managedObjectContext! try await moc.perform { object.completed = true // Capture of 'object' with non-Sendable type 'MySpecialObject' in a '@Sendable' closure try moc.save() } Thanks in advance for your help!
1
1
84
1w
SwiftUI's List backed by CoreData using @FetchRequest fails to update on iOS 26 when compiled with Xcode 26
Hey there! I've been tracking a really weird behavior with a List backed by @FetchRequest from CoreData. When I toggle a bool on the CoreData model, the first time it updates correctly, but if I do it a second time, the UI doesn't re-render as expected. This does not happen if I compile the app using Xcode 16 (targeting both iOS 18 and iOS 26), nor it happens when using Xcode 26 and targeting iOS 18. It only happens when building the app using Xcode 26 and running it on iOS 26. Here are two demos: the first one works as expected, when I toggle the state twice, both times updates. The second one, only on iOS 26, the second toggle fails to re-render. Demo (running from Xcode 16): Demo (running from Xcode 26): The code: import SwiftUI import CoreData @main struct CoreDataTestApp: App { let persistenceController = PersistenceController.shared var body: some Scene { WindowGroup { ContentView() .environment(\.managedObjectContext, persistenceController.container.viewContext) } } } struct ContentView: View { @Environment(\.managedObjectContext) private var viewContext @FetchRequest(sortDescriptors: [NSSortDescriptor(keyPath: \Item.timestamp, ascending: true)]) private var items: FetchedResults<Item> var body: some View { NavigationView { List { ForEach(items) { item in HStack { Text(item.timestamp!.formatted()) Image(systemName: item.isFavorite ? "heart.fill" : "heart").foregroundStyle(.red) }.swipeActions(edge: .leading, allowsFullSwipe: true) { Button(item.isFavorite ? "Unfavorite" : "Favorite", systemImage: item.isFavorite ? "heart" : "heart.fill") { toggleFavoriteStatus(item: item) } } } } .toolbar { ToolbarItem { Button(action: addItem) { Label("Add Item", systemImage: "plus") } } } } } private func addItem() { withAnimation { let newItem = Item(context: viewContext) newItem.timestamp = Date() newItem.isFavorite = Bool.random() try! viewContext.save() } } private func toggleFavoriteStatus(item: Item) { withAnimation { item.isFavorite.toggle() try! viewContext.save() } } } struct PersistenceController { static let shared = PersistenceController() let container: NSPersistentContainer init() { container = NSPersistentContainer(name: "CoreDataTest") container.loadPersistentStores(completionHandler: { _, _ in }) container.viewContext.automaticallyMergesChangesFromParent = true } }
4
0
137
1w
Change to SwiftData ModelContainer causing crashes
I have some models in my app: [SDPlanBrief.self, SDAirport.self, SDChart.self, SDIndividualRunwayAirport.self, SDLocationBrief.self] SDLocationBrief has a @Relationship with SDChart When I went live with my app I didn't have a versioned schema, but quickly had to change that as I needed to add items to my SDPlanBrief Model. The first versioned schema I made included only the model that I had made a change to. static var models: [any PersistentModel.Type] { [SDPlanBrief.self] } I had made zero changes to my model container and the whole time, and it was working fine. The migration worked well and this is what I was using: .modelContainer(for: [SDAirport.self, SDIndividualRunwayAirport.self, SDLocationBrief.self, SDChart.self, SDPlanBrief.self]) I then saw that to do this all properly, I should actually include ALL of my @Models in the versioned schema: enum AllSwiftDataSchemaV3: VersionedSchema { static var models: [any PersistentModel.Type] { [SDPlanBrief.self, SDAirport.self, SDChart.self, SDIndividualRunwayAirport.self, SDLocationBrief.self] } static var versionIdentifier: Schema.Version = .init(2, 0, 0) } extension AllSwiftDataSchemaV3 { @Model class SDPlanBrief { var destination: String etc... init(destination: String, etc...) { self.destination = destination etc... } } @Model class SDAirport { var catABMinima: String etc... init(catABMinima: String etc...) { self.catABMinima = catABMinima etc... } } @Model class SDChart: Identifiable { var key: String etc... var brief: SDLocationBrief? // @Relationship with SDChart init(key: String etc...) { self.key = key etc... } } @Model class SDIndividualRunwayAirport { var icaoCode: String etc... init(icaoCode: String etc...) { self.icaoCode = icaoCode etc... } } @Model class SDLocationBrief: Identifiable { var briefString: String etc... @Relationship(deleteRule: .cascade, inverse: \SDChart.brief) var chartsArray = [SDChart]() init( briefString: String, etc... chartsArray: [SDChart] = [] ) { self.briefString = briefString etc... self.chartsArray = chartsArray } } } This is ALL my models in here btw. I saw also that modelContainer needed updating to work better for versioned schemas. I changed my modelContainer to look like this: actor ModelContainerActor { @MainActor static func container() -> ModelContainer { let schema = Schema( versionedSchema: AllSwiftDataSchemaV3.self ) let configuration = ModelConfiguration() let container = try! ModelContainer( for: schema, migrationPlan: PlanBriefMigrationPlan.self, configurations: configuration ) return container } } and I am passing in like so: .modelContainer(ModelContainerActor.container()) Each time I run the app now, I suddenly get this message a few times in a row: CoreData: error: Attempting to retrieve an NSManagedObjectModel version checksum while the model is still editable. This may result in an unstable verison checksum. Add model to NSPersistentStoreCoordinator and try again. I typealias all of these models too for the most recent V3 version eg: typealias SDPlanBrief = AllSwiftDataSchemaV3.SDPlanBrief Can someone see if I am doing something wrong here? It seems my TestFlight users are experiencing a crash every now and then when certain views load (I assume when accessing @Query objects). Seems its more so when a view loads quickly, like when removing a subscription view where the data may not have had time to load??? Can someone please have a look and help me out.
6
0
197
Jul ’25
Core Data stack in #Playground
I'm using the #Playground macro in Xcode 26.0, running on macOS 26.0. I can get the basics working, but I don't understand how it hooks into the rest of the app, like the App Delete or the Core Data stack. Do we have to create a new Core Data stack, like for SwiftUI Previews, or can it hook into the stack from the main app (if so, how)?
1
0
113
Jul ’25
CoreData crashing on iOS26
Hi, I work on a financial app in Brazil and since Beta 1 we're getting several crashes. We already opened a code level support and a few feedback issues, but haven't got any updates on that yet. We were able to resolve some crashes changing some of our implementation but we aren't able to understand what might be happening with this last one. This is the log we got on console: erro 11:55:41.805875-0300 MyApp CoreData: error: Failed to load NSManagedObjectModel with URL 'file:///private/var/containers/Bundle/Application/0B9F47D9-9B83-4CFF-8202-3718097C92AE/MyApp.app/ServerDrivenModel.momd/' We double checked and the momd is inside the bundle. The same app works on any other iOS version and if we build using Xcode directly (without archiving and installing on an iOS26 device) it works as expected. Have anyone else faced a similar error? Any tips or advice on how we can try to solve that?
2
2
132
Jul ’25
Core Data crash when used in widget extension
I have this very simple PersistenceController setup. It's used in both the main app and widget target. struct PersistenceController { static let shared = PersistenceController() @MainActor static let preview: PersistenceController = { let result = PersistenceController(inMemory: true) let viewContext = result.container.viewContext return result }() let container: NSPersistentContainer /// The main context. var context: NSManagedObjectContext { return container.viewContext } init(inMemory: Bool = false) { container = NSPersistentContainer(name: "Gamery") if inMemory { container.persistentStoreDescriptions.first!.url = URL(fileURLWithPath: "/dev/null") } else { do { let storeURL = try URL.storeURL(forAppGroup: "XXXXXXXXXX", databaseName: "Gamery") let storeDescription = NSPersistentStoreDescription(url: storeURL) /// Enable history tracking for cloud syncing purposes. storeDescription.setOption(true as NSNumber, forKey: NSPersistentHistoryTrackingKey) print("### Persistent container location: \(storeURL)") container.persistentStoreDescriptions = [storeDescription] } catch { print("Failed to retrieve store URL for app group: \(error)") } } container.loadPersistentStores(completionHandler: { (storeDescription, error) in if let error = error as NSError? { Crashlytics.crashlytics().record(error: error) fatalError("Unresolved error \(error), \(error.userInfo)") } }) container.viewContext.automaticallyMergesChangesFromParent = true container.viewContext.mergePolicy = NSMergePolicy.mergeByPropertyObjectTrump #if !WIDGET if !inMemory { do { try container.viewContext.setQueryGenerationFrom(.current) } catch { fatalError("###\(#function): Failed to pin viewContext to the current generation: \(error)") } } PersistentHistoryToken.loadToken() #endif } } I regularly receive crash logs from the widget. I never experienced crashes myself and the widgets work fine. GameryWidgetExtension/PersistenceController.swift:35: Fatal error: Unresolved error Error Domain=NSCocoaErrorDomain Code=256 "The file “Gamery.sqlite” couldn’t be opened." UserInfo={NSFilePath=/private/var/mobile/Containers/Shared/AppGroup/B6A63FE1-ADDC-4A4C-A065-163507E991C6/Gamery.sqlite, NSSQLiteErrorDomain=23}, ["NSSQLiteErrorDomain": 23, "NSFilePath": /private/var/mobile/Containers/Shared/AppGroup/B6A63FE1-ADDC-4A4C-A065-163507E991C6/Gamery.sqlite] I have absolutely no idea what's going on here. Anyone who can help with this?
1
1
72
Jul ’25
EXC_BAD_ACCESS When saving core data
I'm trying to convert some data, then save it back to Core Data. Sometimes this works fine without an issue, but occasionally I'll get an error Thread 1: EXC_BAD_ACCESS (code=1, address=0x0) It seems to occur when saving the core data context. I'm having trouble trying to debug it as it doesn't happen on the same object each time and can't reliably recreate the error Full view code can be found https://pastebin.com/d974V5Si but main functions below var body: some View { VStack { // Visual code here } .onAppear() { DispatchQueue.global(qos: .background).async { while (getHowManyProjectsToUpdate() > 0) { leftToUpdate = getHowManyProjectsToUpdate() updateLocal() } if getHowManyProjectsToUpdate() == 0 { while (getNumberOfFilesInDocumentsDirectory() > 0) { deleteImagesFromDocumentsDirectory() } if getNumberOfFilesInDocumentsDirectory() == 0 { DispatchQueue.main.asyncAfter(deadline: .now()) { withAnimation { self.isActive = true } } } } } } } update local function func updateLocal() { autoreleasepool { let fetchRequest: NSFetchRequest<Project> = Project.fetchRequest() fetchRequest.predicate = NSPredicate(format: "converted = %d", false) fetchRequest.fetchLimit = 1 fetchRequest.sortDescriptors = [NSSortDescriptor(keyPath: \Project.name, ascending: true), NSSortDescriptor(keyPath: \Project.name, ascending: true)] do { let projects = try viewContext.fetch(fetchRequest) for project in projects { currentPicNumber = 0 currentProjectName = project.name ?? "Error loading project" if let projectMain = project.mainPicture { currentProjectImage = getUIImage(picture: projectMain) } if let pictures = project.pictures { projectPicNumber = pictures.count // Get main image if let projectMain = project.mainPicture { if let imgThumbData = convertImageThumb(picture: projectMain) { project.mainPictureData = imgThumbData } } while (getTotalImagesToConvertForProject(project: project ) > 0) { convertImageBatch(project: project) } project.converted = true saveContext() viewContext.refreshAllObjects() } } } catch { print("Fetch Failed") } } } convertImageBatch function func convertImageBatch(project: Project) { autoreleasepool { let fetchRequestPic: NSFetchRequest<Picture> = Picture.fetchRequest() let projectPredicate = NSPredicate(format: "project = %@", project) let dataPredicate = NSPredicate(format: "pictureData == NULL") fetchRequestPic.predicate = NSCompoundPredicate(andPredicateWithSubpredicates: [projectPredicate, dataPredicate]) fetchRequestPic.fetchLimit = 5 fetchRequestPic.sortDescriptors = [NSSortDescriptor(keyPath: \Picture.dateTaken, ascending: true)] do { let pictures = try viewContext.fetch(fetchRequestPic) for picture in pictures { currentPicNumber = currentPicNumber + 1 if let imgData = convertImage(picture: picture), let imgThumbData = convertImageThumb(picture: picture) { // Save Converted picture.pictureData = imgData picture.pictureThumbnailData = imgThumbData // Save Image saveContext() viewContext.refreshAllObjects() } else { viewContext.delete(picture) saveContext() viewContext.refreshAllObjects() } } } catch { print("Fetch Failed") } } } And finally saving func saveContext() { do { try viewContext.save() } catch { let nsError = error as NSError fatalError("Unresolved error \(nsError), \(nsError.userInfo)") } }
6
0
146
Jul ’25
Sorting of FetchResults in TableView broken in xcode 26
Previously, I sorted my FetchResult in a TableView like this: @FetchRequest( sortDescriptors: [SortDescriptor(\.rechnungsDatum, order: .forward)], predicate: NSPredicate(format: "betragEingang == nil OR betragEingang == 0") ) private var verguetungsantraege: FetchedResults&lt;VerguetungsAntraege&gt; ... body ... Table(of:VerguetungsAntraege.self, sortOrder: $verguetungsantraege.sortDescriptors) { TableColumn("date", value:\.rechnungsDatum) { item in Text(Formatters.dateFormatter.string(from: item.rechnungsDatum ?? Date()) ) } .width(120) TableColumn("rechNrKurz", value:\.rechnungsNummer) { item in Text(item.rechnungsNummer ?? "") } .width(120) TableColumn("betrag", value:\.totalSum ) { Text(Formatters.currencyFormatter.string(from: $0.totalSum as NSNumber) ?? "kein Wert") } .width(120) TableColumn("klient") { Text(db.getKlientNameByUUID(id: $0.klient ?? UUID(), moc: moc)) } } rows: { ForEach(Array(verguetungsantraege)) { antrag in TableRow(antrag) } } There seem to be changes here in Xcode 26. In any case, I always get the error message in each line with TableColumn("title", value: \.sortingField) Ambiguous use of 'init(_:value:content:)' Does anyone have any idea what's changed? Unfortunately, the documentation doesn't provide any information.
0
0
129
Jun ’25
Prevent data loss from delayed schema deployment
Hi all, I recently discovered that I forgot to deploy my CloudKit schema changes from development to production - an oversight that unfortunately went unnoticed for 2.5 months. As a result, any data created during that time was never synced to iCloud and remains only in the local CoreData store. Once I pushed the schema to production, CloudKit resumed syncing new changes as expected. However, this leaves me with a gap: there's now a significant amount of data that would be lost if users delete or reinstall the app. Before I attempt to implement a manual backup or migration strategy, I was wondering: Does NSPersistentCloudKitContainer keep track of local changes that couldn't be synced doe to the missing schema and automatically reattempt syncing them now that the schema is live? If not, what would be the best approach to ensure this "orphaned" data gets saved to CloudKit retroactively. Thanks in advance for any guidance or suggestions.
0
0
110
Jun ’25
Crash with NSAttributedString in Core Data
I am trying out the new AttributedString binding with SwiftUI’s TextEditor in iOS26. I need to save this to a Core Data database. Core Data has no AttributedString type, so I set the type of the field to “Transformable”, give it a custom class of NSAttributedString, and set the transformer to NSSecureUnarchiveFromData When I try to save, I first convert the Swift AttributedString to NSAttributedString, and then save the context. Unfortunately I get this error when saving the context, and the save isn't persisted: CoreData: error: SQLCore dispatchRequest: exception handling request: <NSSQLSaveChangesRequestContext: 0x600003721140> , <shared NSSecureUnarchiveFromData transformer> threw while encoding a value. with userInfo of (null) Here's the code that tries to save the attributed string: struct AttributedDetailView: View { @ObservedObject var item: Item @State private var notesText = AttributedString() var body: some View { VStack { TextEditor(text: $notesText) .padding() .onChange(of: notesText) { item.attributedString = NSAttributedString(notesText) } } .onAppear { if let nsattributed = item.attributedString { notesText = AttributedString(nsattributed) } else { notesText = "" } } .task { item.attributedString = NSAttributedString(notesText) do { try item.managedObjectContext?.save() } catch { print("core data save error = \(error)") } } } }
2
0
75
Jun ’25
defaultIsolation option and Core Data
When creating a new project in Xcode 26, the default for defaultIsolation is MainActor. Core Data creates classes for each entity using code gen, but now those classes are also internally marked as MainActor, which causes issues when accessing managed object from a background thread like this. Is there a way to fix this warning or should Xcode actually mark these auto generated classes as nonisolated to make this better? Filed as FB13840800. nonisolated struct BackgroundDataHandler { @concurrent func saveItem() async throws { let context = await PersistenceController.shared.container.newBackgroundContext() try await context.perform { let newGame = Item(context: context) newGame.timestamp = Date.now // Main actor-isolated property 'timestamp' can not be mutated from a nonisolated context; this is an error in the Swift 6 language mode try context.save() } } } Turning code gen off inside the model and creating it manually, with the nonisolated keyword, gets rid of the warning and still works fine. So I guess the auto generated class could adopt this as well? public import Foundation public import CoreData public typealias ItemCoreDataClassSet = NSSet @objc(Item) nonisolated public class Item: NSManagedObject { }
1
0
72
Jun ’25
Core Data, Swift 6, Concurrency and more
I have the following struct doing some simple tasks, running a network request and then saving items to Core Data. Per Xcode 26's new default settings (onisolated(nonsending) & defaultIsolation set to MainActor), the struct and its functions run on the main actor, which works fine and I can even safely omit the context.perform call because of it, which is great. struct DataHandler { func importGames(withIDs ids: [Int]) async throws { ... let context = PersistenceController.shared.container.viewContext for game in games { let newGame = GYGame(context: context) newGame.id = UUID() } try context.save() } } Now, I want to run this in a background thread to increase performance and responsiveness. So I followed this session (https://developer.apple.com/videos/play/wwdc2025/270) and believe the solution is to mark the struct as nonisolated and the function itself as @concurrent. The function now works on a background thread, but I receive a crash: _dispatch_assert_queue_fail. This happens whether I wrap the Core Data calls with context.perform or not. Alongside that I get a few new warnings which I have no idea how to work around. So, what am I doing wrong here? What's the correct way to solve this simple use case with Swift 6's new concurrency stuff and the default main actor isolation in Xcode 26? Curiously enough, when setting onisolated(nonsending) to false & defaultIsolation to non isolating, mimicking the previous behavior, the function works without crashing. nonisolated struct DataHandler { @concurrent func importGames(withIDs ids: [Int]) async throws { ... let context = await PersistenceController.shared.container.newBackgroundContext() for game in games { let newGame = GYGame(context: context) newGame.id = UUID() // Main actor-isolated property 'id' can not be mutated from a nonisolated context; this is an error in the Swift 6 language mode } try context.save() } }
2
0
95
Jun ’25
NSPersistentCloudKitContainer causes crash on watchOS when device is offline
Hi. I'm hoping someone might be able to help us with an issue that's been affecting our standalone watchOS app for some time now. We've encountered consistent crashes on Apple Watch devices when the app enters the background while the device is offline (i.e., no Bluetooth and no Wi-Fi connection). Through extensive testing, we've isolated the problem to the use of NSPersistentCloudKitContainer. When we switch to NSPersistentContainer, the crashes no longer occur. Interestingly, this issue only affects our watchOS app. The same CloudKit-based persistence setup works reliably on our iOS and macOS apps, even when offline. This leads us to believe the issue may be specific to how NSPersistentCloudKitContainer behaves on watchOS when the device is disconnected from the network. We're targeting watchOS 10 and above. We're unsure if this is a misconfiguration on our end or a potential system-level issue, and we would greatly appreciate any insight or guidance.
2
0
88
Jun ’25
How to switch between Core Data Persistent Stores?
What is the best way to switch between Core Data Persistent Stores? My use case is that I have a multi-user app that stores thousands of data items unique to each user. To me, having Persistent Stores for each user seems like the best design to keep their data separate and private. (If anyone believes that storing the data for all users in one Persistent Store is a better design, I'd appreciate hearing from them.) Customers might switch users 5 to 10 times a day. Switching users must be fast, say a second or two at most.
1
0
59
Jun ’25
Crash with NSAttributedString in Core Data
I am trying out the new AttributedString binding with SwiftUI’s TextEditor in iOS26. I need to save this to a Core Data database. Core Data has no AttributedString type, so I set the type of the field to “Transformable”, give it a custom class of NSAttributedString, and set the transformer to NSSecureUnarchiveFromData When I try to save, I first convert the Swift AttributedString to NSAttributedString, and then save the context. Unfortunately I get this error when saving the context, and the save isn't persisted: CoreData: error: SQLCore dispatchRequest: exception handling request: <NSSQLSaveChangesRequestContext: 0x600003721140> , <shared NSSecureUnarchiveFromData transformer> threw while encoding a value. with userInfo of (null) Here's the code that tries to save the attributed string: struct AttributedDetailView: View { @ObservedObject var item: Item @State private var notesText = AttributedString() var body: some View { VStack { TextEditor(text: $notesText) .padding() .onChange(of: notesText) { item.attributedString = NSAttributedString(notesText) } } .onAppear { if let nsattributed = item.attributedString { notesText = AttributedString(nsattributed) } else { notesText = "" } } .task { item.attributedString = NSAttributedString(notesText) do { try item.managedObjectContext?.save() } catch { print("core data save error = \(error)") } } } } This is the attribute setup in the Core Data model editor: Is there a workaround for this? I filed FB17943846 if someone can take a look. Thanks.
2
0
158
Jun ’25
FoundationModels and Core Data
Hi, I have an app that uses Core Data to store user information and display it in various views. I want to know if it's possible to easily integrate this setup with FoundationModels to make it easier for the user to query and manipulate the information, and if so, how would I go about it? Can the model be pointed to the database schema file and the SQLite file sitting in the user's app group container to parse out the information needed? And/or should the NSManagedObjects be made @Generable for better output? Any guidance about this would be useful.
1
0
162
Jun ’25