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

200 Posts
Sort by:

Post

Replies

Boosts

Views

Activity

EXC_CRASH from NSManagedObjectContext executeFetchRequest
Hello, I have an iOS app for which I've received a number of similar crash reports over the last few months. Despite a lot of effort, I haven't been able to replicate the crash myself and I'm finding it difficult to diagnose. The main view of the app loads a list of items from Core Data using @FetchRequest and looking at the logs it appears to me that this is the most likely source of the crash as the call stack includes SwiftUI 0x19c78c368 FetchRequest.update() + 472 (FetchRequest.swift:406). It also appears as if this happens on launch as the crash times and launch times are always very similar. I've attempted lots of things to try and replicate the crash, such as launching the app a lot of times, creating lots of items so that the fetch request has a lot of data to retrieve, performing any other database related actions in the app immediately after launch to try and drive out any concurrency issues and simulating degraded thermal and network conditions for the device. I've included a sample crash report, I'd be very grateful if anyone has any suggestions for diagnosing the issue. Crash Report
2
0
64
52m
How to get notified on CKError.quotaExceeded
Hi all, I have an iOS app which uses CloudKit and the standard NSPersistentCloudKitContainer, which I rely on for syncing app data between the user's devices. If the user's iCloud account is full I can see a log message while debugging in Xcode shortly after startup which looks something like this: error: CoreData+CloudKit: -[NSCloudKitMirroringDelegate _requestAbortedNotInitialized:](2183): <NSCloudKitMirroringDelegate: 0x281ddc1e0> - Never successfully initialized and cannot execute request '<NSCloudKitMirroringExportRequest: 0x2841e00f0> 51383346-87BA-44D8-B527-A0B1EE35A0EF' due to error: <CKError 0x282c50db0: "Partial Failure" (2/1011); "Failed to modify some records"; uuid = 7BA17495-4F05-4AF4-A463-C0DF5A823B2E; container ID = "iCloud.com.neufsters.pangram"; partial errors: { E30B2972-FD4B-4D2A-BD1C-EB6F33F5367D:(com.apple.coredata.cloudkit.zone:__defaultOwner__) = <CKError 0x282c155f0: "Quota Exceeded" (25/2035); server message = "Quota exceeded"; op = FC4D3188D0A46ABC; uuid = 7BA17495-4F05-4AF4-A463-C0DF5A823B2E; Retry after 315.0 seconds> 2FC9A487-D630-444D-B7F4-27A0F3A6B46E:(com.apple.coredata.cloudkit.zone:__defaultOwner__) = <CKError 0x282c52820: "Quota Exceeded" (25/2035); server message = "Quota exceeded"; op = FC4D3188D0A46ABC; uuid = 7BA17495-4F05-4AF4-A463-C0DF5A823B2E; Retry after 315.0 seconds> 903DD6A0-0BD8-46C0-84FB-E89797514D9F:(com.apple.coredata.cloudkit.zone:__defaultOwner__) = <CKError 0x282c513e0: "Quota Exceeded" (25/2035); server message = "Quota exceeded"; op = FC4D3188D0A46ABC; uuid = 7BA17495-4F05-4AF4-A463-C0DF5A823B2E; Retry after 315.0 seconds> }> I would like to know how I can get a callback of some sort so I can run code if this CloudKit/CoreData error happens. In particular I'd like to put up some sort of warning to the user letting them know their data isn't going to sync. Please note that I'm not looking for how to do error handling as a result of a user-initiated CloudKit API call. I'm looking for how to get notified when the background syncing logs errors like the above. Thanks, Russ
5
2
512
9h
Core Data crashes when attempting to establish relationship to an entity with derived attribute in the background
I have recently moved some of my data save operations from the view context to background contexts. Since the switch, some (but not all) of my users are reporting that the background save operations crash 100% of the time. After researching, I have narrowed it down to the fact that these save operations involve establishing a relationship to an entity with a derived attribute. An example is shown below: try await CoreDataStack.shared.performBackgroundTask { context in var transaction = Transaction(context: context) transaction.amount = NSDecimalNumber(decimal: 0) transaction.id = UUID() let account = Account.account(withName: "Default", in: context) transaction.account = account try context.save() } // <= Crashes! In the above example, each Transaction has a to-one relationship to an Account, and the latter has a to-many relationship the the former. Account has a derived attribute called balance that is calculated using the expression sum:(transactionItems.amount). The would then crash when the performBackgroundTask block exits (after the save() operation returns): Thread 4 Crashed: 0 libobjc.A.dylib 0x00000001850ae00c objc_release_x8 + 8 1 CoreData 0x00000001900d8cfc -[_CDSnapshot dealloc] + 72 (_CDSnapshot.m:691) 2 CoreData 0x00000001900d8b68 _NSQLRow_dealloc_standard + 48 (NSSQLRow.m:156) 3 CoreFoundation 0x0000000187d72228 __CFBasicHashRemoveValue + 192 (CFBasicHash.c:1332) 4 CoreFoundation 0x0000000187d7212c CFBasicHashRemoveValue + 452 (CFBasicHash.c:1418) 5 CoreFoundation 0x0000000187d71638 CFDictionaryRemoveValue + 196 (CFDictionary.c:477) 6 CoreData 0x00000001900f6fa8 -[NSPersistentStoreCache decrementRefCountForObjectID:] + 96 (NSPersistentStoreCache.m:120) 7 CoreData 0x00000001900f6eec -[NSSQLCore managedObjectContextDidUnregisterObjectsWithIDs:generation:] + 172 (NSSQLCore.m:4329) 8 CoreData 0x00000001900f30f4 0x1900d6000 + 119028 9 CoreData 0x00000001900f4d74 gutsOfBlockToNSPersistentStoreCoordinatorPerform + 204 (NSPersistentStoreCoordinator.m:404) 10 libdispatch.dylib 0x000000018fe9b0d8 _dispatch_client_callout + 20 (object.m:576) 11 libdispatch.dylib 0x000000018fea26e0 _dispatch_lane_serial_drain + 744 (queue.c:3934) 12 libdispatch.dylib 0x000000018fea31e8 _dispatch_lane_invoke + 380 (queue.c:4025) 13 libdispatch.dylib 0x000000018feae258 _dispatch_root_queue_drain_deferred_wlh + 288 (queue.c:7185) 14 libdispatch.dylib 0x000000018feadaa4 _dispatch_workloop_worker_thread + 532 (queue.c:6779) 15 libsystem_pthread.dylib 0x000000020f3c0c7c _pthread_wqthread + 288 (pthread.c:2696) 16 libsystem_pthread.dylib 0x000000020f3bd488 start_wqthread + 8 performBackgroundTask is defined as: func performBackgroundTask<T>(_ block: @escaping (NSManagedObjectContext) throws -> T) async rethrows -> T { try await container.performBackgroundTask { context in context.transactionAuthor = appTransactionAuthorName context.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy return try block(context) } } Things to note: If I do not establish the relationship to Account from Transaction, the crash doesn't happen; if I uncheck derived on the balance attribute of Account, the crash also does not happen. For those users who are experiencing the crash, the crash rate is 100%; for those who aren't experiencing the crash, the crash never happens. So it's either 100% or 0%. I have double checked all concurrency usages and all operations are performed within NSPersistentCloudKitContainer's performBackgroundTaskmethod, so it's probably not a threading issue. I have also tried ASan, Core Data's concurrency debug, as well as Zombie objects to no avail. The crash seems to be related to a user's existing data. While I couldn't reproduce the crash on my own database, once I replaced the underlying SQLite file with one of my crashing user's, the crash is 100% reproducible. I am at my wit's end here. Is this an internal Core Data bug, or am I doing something incorrectly? Any help is greatly appreciated!
1
3
132
1d
Recommendations/Advice on Core Data template entity approach
Prerequisites I have three entities: Record, Header, and Row. Record: id index date children (one-to-many relationship with Header entities) Header: id index title parent (Record) (Is null if this Header is a subheader) headerParent (Header) (Is null if this Header is not a subheader) subheaders (one-to-many relationship with Header entities) children (one-to-many relationship with Row entities) Row: id index title value parent (Header) Issue I need to have default data in these entities. When creating a new Record, I want it to copy all default entity data (except for the Row's value) to generate a new Record ready for new notes. Additionally, if the order (index) of the entities' data or their titles are updated, I want the default data to update automatically so the user doesn't have to make these changes manually every time. Proposed Solution My approach is to add a field called isBaseEntity to each entity. When isBaseEntity is true, this entity contains the default information. I would then update this base entity with any changes made to the non-base ones. Additionally, I would exclude this base entity when fetching the rest of the data, as it serves as the default template. Question Is this a good and efficient approach? Do you have any other suggestions or recommendations for improving this? I would really appreciate any help you can provide.
0
0
64
2d
Public and Private CK sync failure, macOS mistake = add data before indexing
I have a Multiplatform app for iOS and macOS targets. I am using CloudKit with CoreData and have successfully established a private and public database. The app has successfully synced private and public data for months between macOS (dev machine), an iPhone 13 Pro and an iPad Pro 12.9inch 2nd gen. The public data also syncs perfectly to simulator instances running under other iCloud accounts. Recently I added a new entity in the public DB and here is where I seemed to have made a mistake. I entered data into the new public database via my developer UI built into the macOS app running on my MBP before I indexed the necessary fields. Side note - I find it necessary to index the following for each Entity to ensure iCloud sync works as expected on all devices... modifiedTimestamp - Queryable modifiedTimestamp - Sortable recordName - Queryable Realising my mistake, I indexed the above CKRecord fields for the new Entity. Since then, the macOS target has remained in some way "frozen" (for want of a better term). I can add new public or private records in the macOS app but they do not propagate to the public or private stores in iCloud. I have attempted many fixed, some summarised below: clean build folder from Xcode; remove all files from the folder /Users//Library/Containers/, place in recycle bin, empty recycle bin, then build and run; build and run on iPhone and iPad targets to ensure all apps are current dev version, then repeat above processes. I've read through the console logging when I build and run the macOS app many many times to see whether I can find any hint. The closest thing I can find is... BOOL _NSPersistentUIDeleteItemAtFileURL(NSURL *const __strong) Failed to stat item: file:///Users/<me>/Library/Containers/com.me.AppName/Data/Library/Saved%20Application%20State/com.me.AppName.savedState/restorecount.plist but my research on this and other forums suggests this is not relevant. Through this, the app still functions as expected on iOS devices and both private and public database additions and modifications propagate to iCloud stores and to other devices. I expect that removing the macOS app entirely from my dev machine would trigger a complete sync with all existing data. Imagine I bought a new macOS device and chose to install my app where before I had run this only on my iOS devices. My current problem suggests that I could not do this, but I know that this is not the intended behaviour. This scenario makes me think there is a setting file for my macOS app that I'm not aware of and that this impeding the sync of all existing app data back to the fresh install of the macOS app? But that is a wild guess. Running public releases (no betas) Xcode 15.4 (15F31d) macOS Sonoma 14.5 physical iOS devices running iOS 17.5.1 Any words of wisdom on how I might go about trying to solve this problem please?
1
0
158
2d
Crash when accessing Core Data because file couldn't be opened
We have a crash regarding to Core Data access that was not reproducible in our side but the crash count keeps increasing with the last stack trace is assertionFailure from Apple internal SDK. The last stack trace before the assertionFailure by system is our code initializing CoreData in DataContainer.init(name:bundle:inMemory:) where we will try to access CoreData and the error message we found from our 3rd party crash reporter is something like this DataStore/DataContainer.swift:30: Fatal error: Unresolved error Error Domain=NSCocoaErrorDomain Code=256 "The file “Content.sqlite” couldn’t be opened. UserInfo={NSFilePath=/var/mobile/Containers/Data/Application/9DBF262C-851A-486B-90CC-4397A8896525/Library/Application Support/Content.sqlite, NSSQLiteErrorDomain=13}, ["NSSQLiteErrorDomain": 13, "NSFilePath": /var/mobile/Containers/Data/Application/9DBF262C-851A-486B-90CC-4397A8896525/Library/Application Support/Content.sqlite] That sqlite file is supposed to be file used by Core Data (since we have no other code that access it) and we are quite confused on why sometimes the CoreData cannot be accessed with that kind of error message. So far, we still have no idea to reproduce it and what do to resolve it. I have submitted the report with bug number: FB14433998 I attached an example of the crash report here too. Please gave us insight on why it happened and how we can prevent it from happening again. crash log 1.crash
0
0
85
3d
SwiftData - error: Error: Persistent History (2) has to be truncated due to the following entities being removed: ( A )
I'm having trouble resolving the error. If I save data in view A and open view B, I get an error. If I open only view A, or only view B, there is no problem, but when I open a second view (A to B, B to A, etc.) I get an error. Attached is the code that reproduces the problem. We would appreciate your cooperation. No simulator is used. Xcode: Version 15.4 (15F31d) iPone11: 17.5.1 Thank you. Error error: Error: Persistent History (2) has to be truncated due to the following entities being removed: ( A ) warning: Warning: Dropping Indexes for Persistent History warning: Warning: Dropping Transactions prior to 2 for Persistent History warning: Warning: Dropping Changes prior to TransactionID 2 for Persistent History Code import SwiftUI import SwiftData @main struct issueApp: App { var body: some Scene { WindowGroup { ContentView() .modelContainer(for: [A.self, B.self]) } } } import SwiftUI import SwiftData struct ContentView: View { @State var showAView: Bool = false @State var showBView: Bool = false var body: some View { VStack { Button("show A"){ showAView.toggle() } .sheet(isPresented: $showAView){ AView() } Button("show B"){ showBView.toggle() } .sheet(isPresented: $showBView){ BView() } } } } struct AView: View { @Environment(\.modelContext) var context @Query private var list: [A] let query = QueryData<A>() var body: some View { VStack { if list.count > 0 { VStack { List { ForEach(list, id: \.number){ item in VStack { Text(item.number) } } } Button("clear"){ try? context.delete(model: A.self) } } } else { Button("set"){ query.set(data: A(number: "1")) } } } } } struct BView: View { @Environment(\.modelContext) var context @Query private var list: [B] let query = QueryData<B>() var body: some View { VStack { if list.count > 0 { VStack { List { ForEach(list, id: \.number){ item in VStack { Text(item.number) } } } Button("clear"){ try? context.delete(model: B.self) } } } else { Button("set"){ query.set(data: B(number: "1")) } } } } } class QueryData<T: PersistentModel> { private var container: ModelContainer? init() { self.container = try? ModelContainer(for: T.self) } func set(data: T) { guard let container = self.container else { return } let context = ModelContext(container) do { try context.delete(model: T.self) context.insert(data) try context.save() } catch { print("error: \(error)") } } } @Model final class A { var number: String init(number: String) { self.number = number } } @Model final class B { var number: String init(number: String) { self.number = number } }
2
0
188
6d
Core Data Crash: Could not merge changes
We have one Persistent store coordinator(PSC). On top of this we have two managed object contexts(MOC), one with private queue concurrency(bgMOC) persistentContainer.newBackgroundContext() and another with main queue concurrency(mainMOC). persistentContainer.viewContext We have verified that only one PSC is connected to the sqlite. We only have one PSC object and only one bgMOC. We always use bgMOC for writes. And main for UI just reads and UI purposes. We strictly follow access of managed objects in the contexts .perform { } always. Problem: We see lots of Merge Conflicts We have printed the conflict attributes and found object snapshot is always null cached snapshot is printed persisted snapshot is printed Our findings: Sometimes cached snapshot is same as persisted snapshot and sometimes there is a diff in some property(not sure relationships diff as snapshot dont have these info). The NSManagedObject current values match the persistent store snapshot always. In one of the logs we concluded that the cachedRow was stale, and both the managed object and persisted values were same with newer values. How do we proceed to fix this? Is cached row supposed to be synchronously updated with every save that happens? We dont want to put a merge policy as we think conflicts should not happen at first place as we are always writing via same bgMoc Additional information Our app does lots of quick(within 1-2 ms) bgMoc.perform { change, bgMoc.save } back to back and on same objets as well. Some places we have noticed if we try to dump a same change two times in quick succession via same bgMoc this crash happens. But we were not able to reproduce this on dev systems. something like bgMoc.perform { obj1.changeX, bgMoc.save } bgMoc.perform {obj1. changeX, bgMoc.save } We also do bgMocPerorm inside bgMoc.perofrm like this bgMoc.perform { on some managed objects validate a condition early exist if fails. onSomeOtherThreadComputeSomeStuff { success in bgMoc.perform { someChange bMoc.save() } } } Crash log [Debug] [NSManagedObjectContext 0x303b11e10] [NSManagedObjectContext+Enhancements.swift:32] > Save error. Error : Error Domain=NSCocoaErrorDomain Code=133020 "Could not merge changes." UserInfo={conflictList=( "NSMergeConflict (0x301aa97c0) for NSManagedObject (0x302045c70) with objectID '0x8d881a3c1b3524ba <x-coredata://412EE632-D802-451E-99DF-50ADF230B800/MailThread/p1416>' with oldVersion = 2 and newVersion = 3 and old cached row = {\n attachmentCount = 0;\n firstScheduledDate = \"<null>\";\n id = 2164154918090767;\n lastMessageDraftDate = \"<null>\";\n lastMessageReceivedDate = \"2024-07-16 18:31:34 +0000\";\n lastMessageSentDate = \"<null>\";\n messageCount = 1;\n rawFlags = 0;\n snippet = \"snippet1\";\n subject = \"subject1\";\n transactionIdAsNumber = 2164277798615057;\n umc = 1;\n} and new database row = {\n attachmentCount = 0;\n firstScheduledDate = \"<null>\";\n id = 2164154918090767;\n lastMessageDraftDate = \"<null>\";\n lastMessageReceivedDate = \"2024-07-16 18:31:34 +0000\";\n lastMessageSentDate = \"<null>\";\n messageCount = 1;\n rawFlags = 0;\n snippet = \"snippet1\";\n subject = \"subject1\";\n transactionIdAsNumber = 2164277798615057;\n umc = 1;\n}"
0
0
121
1w
Regression macOS 15 beta: NSTableViewDiffableDataSource does not call the 'cellProvider' when the data of a visible cell changes
In one of my apps, I use NSTableViewDiffableDataSource in tandem with NSFetchedResultsController, which provides the necessary snapshots. This works great in macOS 14.5. However in latest macOS 15 betas, NSTableViewDiffableDataSource does not call the 'cellProvider' completion handler anymore when the data of a visible cell changes. When data of a visible cell changes, the didChangeContentWith method of NSFetchedResultsController is called correctly, but applying the provided snapshot doesn’t result in calling the said 'cellProvider' completion handler. This looks a rollback to the early state of this API in 2020. It concerns this piece of code: dataSource = NSTableViewDiffableDataSource(tableView: tableView, cellProvider: { (tableView, tableColumn, row, item) -> NSView in // Return a cell view with data }) Does anyone know a solution or workaround to get animated updates of visible cells working in macOS 15 beta? Yes, applying the snapshot without animation works, but that’s not where NSTableViewDiffableDataSource is designed for. In case an Apple engineer reads this: Looking at the sample code associated with FB13931189, is there anything wrongly implemented that prevents calling the 'cellProvider' method for visible cells? Is this perhaps actually a bug of NSFetchedResultsController? I’m asking this because NSCollectionViewDiffableDataSource does have a very similar problem (FB13943853). PS Yes, this post looks very similar to https://developer.apple.com/forums/thread/759381#759381021, because the problem is identical except that concerns NSCollectionViewDiffableDataSource.
0
0
160
2w
Regression macOS 15 beta: NSCollectionViewDiffableDataSource does not call the 'itemProvider' when the data of a visible item changes
In one of my apps, I use NSCollectionViewDiffableDataSource in tandem with NSFetchedResultsController, which provides the necessary snapshots. This works great in macOS 14.5. However, when updating data in Core Data related to a visible item in a NSCollectionView, the NSCollectionViewDiffableDataSource no longer calls the ‘itemProvider’ closure of the diffable data source when using macOS 15 Seed 3, after applying a snapshot with animation. As a result of this, the collection view does not update visible items when the related data changes. I’m talking about this piece of code which is no longer called when it concerns a visible item: dataSource = NSCollectionViewDiffableDataSource<String, NSManagedObjectID>(collectionView: collectionView, itemProvider: { // Return an NSCollectionViewItem here }) Does anyone know a workaround or solution to get updating of visible cells working in macOS 15 Seed 3, without losing animated updates? In case an Apple engineer is reading this: Are there any related API changes that must be taken into account? Is this perhaps actually a bug of NSFetchedResultsController? I’m asking this because NSTableViewDiffableDataSource does have a very similar problem in macOS 15 beta. See also FB13943853
0
0
148
2w
NSPersistentCloudkitContainer Memory Leak -> Crash? (iOS 15 beta 4 & 5)
Background I have an established app in the App Store which has been using NSPersistentCloudkitContainer since iOS 13 without any issues. I've been running my app normally on an iOS device running the iOS 15 betas, mainly to see problems arise before my users see them. Ever since iOS 15 (beta 4) my app has failed to sync changes - no matter how small the change. An upload 'starts' but never completes. After a minute or so the app quits to the Home Screen and no useful information can be gleaned from crash reports. Until now I've had no idea what's going on. Possible Bug in the API? I've managed to replicate this behaviour on the simulator and on another device when building my app with Xcode 13 (beta 5) on iOS 15 (beta 5). It appears that NSPersistentCloudkitContainer has a memory leak and keeps ramping up the RAM consumption (and CPU at 100%) until the operating system kills the app. No code of mine is running. I'm not really an expert on these things and I tried to use Instruments to see if that would show me anything. It appears to be related to NSCloudkitMirroringDelegate getting 'stuck' somehow but I have no idea what to do with this information. My Core Data database is not tiny, but not massive by any means and NSPersistentCloudkitContainer has had no problems syncing to iCloud prior to iOS 15 (beta 4). If I restore my App Data (from an external backup file - 700MB with lots of many-many, many-one relationships, ckAssets, etc.) the data all gets added to Core Data without an issue at all. The console log (see below) then shows that a sync is created, scheduled & then started... but no data is uploaded. At this point the memory consumption starts and all I see is 'backgroundTask' warnings appear (only related to CloudKit) with no code of mine running. CoreData: CloudKit: CoreData+CloudKit: -[PFCloudKitExporter analyzeHistoryInStore:withManagedObjectContext:error:](501): <PFCloudKitExporter: 0x600000301450>: Exporting changes since (0): <NSPersistentHistoryToken - { "4B90A437-3D96-4AC9-A27A-E0F633CE5D9D" = 906; }> CoreData: CloudKit: CoreData+CloudKit: -[PFCloudKitExportContext processAnalyzedHistoryInStore:inManagedObjectContext:error:]_block_invoke_3(251): Finished processing analyzed history with 29501 metadata objects to create, 0 deleted rows without metadata. CoreData: CloudKit: CoreData+CloudKit: -[NSCloudKitMirroringDelegate _scheduleAutomatedExportWithLabel:activity:completionHandler:](2800): <NSCloudKitMirroringDelegate: 0x6000015515c0> - Beginning automated export - ExportActivity: <CKSchedulerActivity: 0x60000032c500; containerID=<CKContainerID: 0x600002ed3240; containerIdentifier=iCloud.com.nitramluap.Somnus, containerEnvironment="Sandbox">, identifier=com.apple.coredata.cloudkit.activity.export.4B90A437-3D96-4AC9-A27A-E0F633CE5D9D, priority=2, xpcActivityCriteriaOverrides={ Priority=Utility }> CoreData: CloudKit: CoreData+CloudKit: -[NSCloudKitMirroringDelegate executeMirroringRequest:error:](765): <NSCloudKitMirroringDelegate: 0x6000015515c0>: Asked to execute request: <NSCloudKitMirroringExportRequest: 0x600002ed2a30> CBE1852D-7793-46B6-8314-A681D2038B38 2021-08-13 08:41:01.518422+1000 Somnus[11058:671570] [BackgroundTask] Background Task 68 ("CoreData: CloudKit Export"), was created over 30 seconds ago. In applications running in the background, this creates a risk of termination. Remember to call UIApplication.endBackgroundTask(_:) for your task in a timely manner to avoid this. 2021-08-13 08:41:03.519455+1000 Somnus[11058:671570] [BackgroundTask] Background Task 154 ("CoreData: CloudKit Scheduling"), was created over 30 seconds ago. In applications running in the background, this creates a risk of termination. Remember to call UIApplication.endBackgroundTask(_:) for your task in a timely manner to avoid this. Just wondering if anyone else is having a similar issue? It never had a problem syncing an initial database restore prior to iOS 15 (beta 4) and the problems started right after installing iOS 15 (beta 4). I've submitted this to Apple Feedback and am awaiting a response (FB9412346). If this is unfixable I'm in real trouble (and my users are going to be livid). Thanks in advance!
22
0
10k
2w
Crash in Widget extension
Hi everyone! I'm seeking help to understand crashes that, as I can see, come from the widget extension. The brief stack trace that I can see under Xcode -> Window -> Organizer -> [My App] -> Crashes is pretty short (see attachment). My widgets do fetch request to Core Data, but the operation is performed on the background thread and data is lightweight. I have been debugging for days, but haven't found any weak code blocks that might take too much memory or crash due to simple language issues. Will appreciate any help! In the crash report file, I see the following logs (highlight a few of them due to lines limit): Incident Identifier: 62A28083-43EE-47F2-A2E0-89A1FA89744A Hardware Model: iPhone13,2 Process: MyAppWidgetsExtension [28359] Identifier: MyAppWidgets Version: 2.16.0 (290) OS Version: iPhone OS 17.4.1 (21E236) Exception Type: EXC_CRASH (SIGKILL) Termination Reason: RUNNINGBOARD 0xdead10cc Thread 0 Crashed: 0 libsystem_kernel.dylib 0x00000001e05c5af8 mach_msg2_trap + 8 (:-1) 1 libsystem_kernel.dylib 0x00000001e05c5890 mach_msg2_internal + 80 (mach_msg.c:201) 2 libsystem_kernel.dylib 0x00000001e05c57a8 mach_msg_overwrite + 436 (mach_msg.c:0) 3 libsystem_kernel.dylib 0x00000001e05c55e8 mach_msg + 24 (mach_msg.c:323) 4 CoreFoundation 0x00000001980a001c __CFRunLoopServiceMachPort + 160 (CFRunLoop.c:2624) 5 CoreFoundation 0x000000019809df04 __CFRunLoopRun + 1208 (CFRunLoop.c:3007) 6 CoreFoundation 0x000000019809d968 CFRunLoopRunSpecific + 608 (CFRunLoop.c:3420) 7 Foundation 0x0000000196f2c4a8 -[NSRunLoop(NSRunLoop) runMode:beforeDate:] + 212 (NSRunLoop.m:373) 8 Foundation 0x0000000196f2aff0 -[NSRunLoop(NSRunLoop) run] + 64 (NSRunLoop.m:398) 9 libxpc.dylib 0x00000001f40aa26c _xpc_objc_main + 336 (main.m:267) 10 libxpc.dylib 0x00000001f40ac7e4 _xpc_main + 64 (init.c:1294) 11 libxpc.dylib 0x00000001f40ac7a4 xpc_bs_main + 16 (init.c:1310) 12 BoardServices 0x00000001b0d38240 +[BSServicesConfiguration activateXPCService] + 68 (BSServicesConfiguration.m:113) 13 ExtensionFoundation 0x00000001a70bbdf0 -[_EXRunningExtension resume] + 260 (EXRunningExtension.m:298) 14 ExtensionFoundation 0x00000001a70bbc38 -[_EXRunningExtension startWithArguments:count:] + 396 (EXRunningExtension.m:269) 15 ExtensionFoundation 0x00000001a70cfa30 EXExtensionMain + 220 (EXExtensionMain.m:34) 16 Foundation 0x0000000197665ed4 NSExtensionMain + 204 (NSExtensionMain.m:21) 17 dyld 0x00000001bb5bed84 start + 2240 (dyldMain.cpp:1298) Thread 2: 0 libsystem_kernel.dylib 0x00000001e05d381c guarded_pwrite_np + 8 (:-1) 1 libsqlite3.dylib 0x00000001c1ddc158 seekAndWrite + 456 (sqlite3.c:44255) 2 libsqlite3.dylib 0x00000001c1d95908 unixWrite + 180 (sqlite3.c:44333) 3 libsqlite3.dylib 0x00000001c1de4574 pagerWalFrames + 868 (sqlite3.c:66940) 4 libsqlite3.dylib 0x00000001c1d95628 sqlite3PagerCommitPhaseOne + 316 (sqlite3.c:70256) 5 libsqlite3.dylib 0x00000001c1d85d7c sqlite3BtreeCommitPhaseOne + 172 (sqlite3.c:80934) 6 libsqlite3.dylib 0x00000001c1d85944 vdbeCommit + 1136 (sqlite3.c:93952) 7 libsqlite3.dylib 0x00000001c1d5ec74 sqlite3VdbeHalt + 1352 (sqlite3.c:94362) 8 libsqlite3.dylib 0x00000001c1d7fd04 sqlite3VdbeExec + 42952 (sqlite3.c:103728) 9 libsqlite3.dylib 0x00000001c1d74c80 sqlite3_step + 964 (sqlite3.c:97699) 10 CoreData 0x00000001a01ba0e0 _execute + 128 (NSSQLiteConnection.m:4573) 11 CoreData 0x00000001a01e5510 -[NSSQLiteConnection commitTransaction] + 596 (NSSQLiteConnection.m:3250) 12 CoreData 0x00000001a040aac0 _executeBatchUpdateRequest + 1216 (NSSQLCore_Functions.m:1110) 13 CoreData 0x00000001a030a240 -[NSSQLBatchUpdateRequestContext executeRequestCore:] + 32 (NSSQLBatchUpdateRequestContext.m:88) 14 CoreData 0x00000001a01c8508 -[NSSQLStoreRequestContext executeRequestUsingConnection:] + 252 (NSSQLStoreRequestContext.m:183) 15 CoreData 0x00000001a01c82b4 __52-[NSSQLDefaultConnectionManager handleStoreRequest:]_block_invoke + 60 (NSSQLConnectionManager.m:302) 16 CoreData 0x00000001a01c81ec __37-[NSSQLiteConnection performAndWait:]_block_invoke + 48 (NSSQLiteConnection.m:733) 17 libdispatch.dylib 0x000000019ff66dd4 _dispatch_client_callout + 20 (object.m:576) 18 libdispatch.dylib 0x000000019ff762c4 _dispatch_lane_barrier_sync_invoke_and_complete + 56 (queue.c:1100) 19 CoreData 0x00000001a01de8d0 -[NSSQLiteConnection performAndWait:] + 176 (NSSQLiteConnection.m:730) 20 CoreData 0x00000001a019d094 -[NSSQLDefaultConnectionManager handleStoreRequest:] + 248 (NSSQLConnectionManager.m:297) 21 CoreData 0x00000001a019cf64 -[NSSQLCoreDispatchManager routeStoreRequest:] + 228 (NSSQLCoreDispatchManager.m:60) 22 CoreData 0x00000001a019cd68 -[NSSQLCore dispatchRequest:withRetries:] + 172 (NSSQLCore.m:3975) 23 CoreData 0x00000001a01bc034 -[NSSQLCore executeRequest:withContext:error:] + 1208 (NSSQLCore.m:2951) 24 CoreData 0x00000001a01d06a0 __65-[NSPersistentStoreCoordinator executeRequest:withContext:error:]_block_invoke.541 + 4156 (NSPersistentStoreCoordinator.m:2994) 25 CoreData 0x00000001a01cf57c -[NSPersistentStoreCoordinator _routeHeavyweightBlock:] + 264 (NSPersistentStoreCoordinator.m:641) 26 CoreData 0x00000001a01abc48 -[NSPersistentStoreCoordinator executeRequest:withContext:error:] + 1048 (NSPersistentStoreCoordinator.m:2768) 27 CoreData 0x00000001a018bbdc -[NSManagedObjectContext executeRequest:error:] + 700 (NSManagedObjectContext.m:2044) 28 CoreData 0x00000001a0265be8 __116+[NSCKRecordMetadata batchUpdateMetadataMatchingEntityIdsAndPKs:withUpdates:inStore:withManagedObjectContext:error:]_block_invoke + 128 (NSCKRecordMetadata.m:744) 29 CoreFoundation 0x000000019806dfb4 __NSDICTIONARY_IS_CALLING_OUT_TO_A_BLOCK__ + 24 (NSDictionaryHelpers.m:10) 30 CoreFoundation 0x000000019806de2c -[__NSDictionaryM enumerateKeysAndObjectsWithOptions:usingBlock:] + 288 (NSDictionaryM.m:271) 31 CoreData 0x00000001a0265970 +[NSCKRecordMetadata batchUpdateMetadataMatchingEntityIdsAndPKs:
4
0
330
2w
How to save to specific stores/configurations in Core Data
I'm currently syncing core data with the CloudKit private and public databases, as you can see in the code below, I'm saving the private database in the default configuration in Core Data and the public in a configuration called Public everything works fine when NSPersistentCloudKitContainer syncs, what I'm having an issue with is trying to save to the public data store PublicStore, for instance when I try to save with func createIconImage(imageName: String) it saves the image to the "default" store, not the PublicStore(Public configuration). What could I do to make the createIconImage() function save to the PublicStore sqlite database? class CoreDataManager: ObservableObject{ static let instance = CoreDataManager() private let queue = DispatchQueue(label: "CoreDataManagerQueue") @AppStorage(UserDefaults.Keys.iCloudSyncKey) private var iCloudSync = false lazy var context: NSManagedObjectContext = { return container.viewContext }() lazy var container: NSPersistentContainer = { return setupContainer() }() init(inMemory: Bool = false){ if inMemory { container.persistentStoreDescriptions.first!.url = URL(fileURLWithPath: "/dev/null") } } func updateCloudKitContainer() { queue.sync { container = setupContainer() } } private func getDocumentsDirectory() -> URL { return FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0] } private func getStoreURL(for storeName: String) -> URL { return getDocumentsDirectory().appendingPathComponent("\(storeName).sqlite") } func setupContainer()->NSPersistentContainer{ let container = NSPersistentCloudKitContainer(name: "CoreDataContainer") let cloudKitContainerIdentifier = "iCloud.com.example.MyAppName" guard let description = container.persistentStoreDescriptions.first else{ fatalError("###\(#function): Failed to retrieve a persistent store description.") } description.setOption(true as NSNumber, forKey: NSPersistentHistoryTrackingKey) description.setOption(true as NSNumber, forKey: NSPersistentStoreRemoteChangeNotificationPostOptionKey) if iCloudSync{ if description.cloudKitContainerOptions == nil { let options = NSPersistentCloudKitContainerOptions(containerIdentifier: cloudKitContainerIdentifier) description.cloudKitContainerOptions = options } }else{ print("Turning iCloud Sync OFF... ") description.cloudKitContainerOptions = nil } // Setup public database let publicDescription = NSPersistentStoreDescription(url: getStoreURL(for: "PublicStore")) publicDescription.configuration = "Public" // this is the configuration name if publicDescription.cloudKitContainerOptions == nil { let publicOptions = NSPersistentCloudKitContainerOptions(containerIdentifier: cloudKitContainerIdentifier) publicOptions.databaseScope = .public publicDescription.cloudKitContainerOptions = publicOptions } container.persistentStoreDescriptions.append(publicDescription) container.loadPersistentStores { (description, error) in if let error = error{ print("Error loading Core Data. \(error)") } } container.viewContext.automaticallyMergesChangesFromParent = true container.viewContext.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy return container } func save(){ do{ try context.save() //print("Saved successfully!") }catch let error{ print("Error saving Core Data. \(error.localizedDescription)") } } } class PublicViewModel: ObservableObject { let manager: CoreDataManager @Published var publicIcons: [PublicServiceIconImage] = [] init(coreDataManager: CoreDataManager = .instance) { self.manager = coreDataManager } func createIconImage(imageName: String) { let newImage = PublicServiceIconImage(context: manager.context) newImage.imageName = imageName newImage.id = UUID() save() } func save() { self.manager.save() } }
1
0
217
2w
Core Data Error
Hi the Log is showing the following error after the app adds data to Core Data from a sheetView: CoreData: error: CoreData+CloudKit: -[NSCloudKitMirroringDelegate tearDown:]_block_invoke(782): <NSCloudKitMirroringDelegate: 0x28379abc0>: Told to tear down with reason: Store Removed I can't seem to find a reference to what is going on. Can someone point me in the right direction? Thanks. Blessings, --Mark
1
0
532
2w
SwiftData fatal error "Never access a full future backing data"
My app started crashing a ton with Xcode 16 beta 1 / iOS 18 because of "Thread 1: Fatal error: Never access a full future backing data". I was hoping this would be resolved with beta 2, but unfortunately this is not the case. I'm having a tough time reproducing this bug in a small sample project – I'd appreciate any hints as to what might be causing this. Full error: Thread 1: Fatal error: Never access a full future backing data - PersistentIdentifier(id: SwiftData.PersistentIdentifier.ID(url: x-coredata://10A5A93C-DC7F-40F3-92DB-F4125E1C7A73/MyType/p2), implementation: SwiftData.PersistentIdentifierImplementation) with Optional(3BF44A2D-256B-4C40-AF40-9B7518FD9FE6)
5
4
446
2w
Tokenised text search in SwiftData help
The SwiftData predicate documentation says that it supports the contains(where:) sequence operation in addition to the contains(_:) string comparison but when I put them together in a predicate to try and perform a tokenised search I get a runtime error. Unsupported subquery collection expression type (NSInvalidArgumentException) I need to be able to search for items that contain at least one of the search tokens, this functionality is critical to my app. Any suggestions are appreciated. Also does anyone with experience with CoreData know if this is possible to do in CoreData with NSPredicate? import SwiftData @Model final class Item { var textString: String = "" init() {} } func search(tokens: Set<String>, context: ModelContext) throws -> [Item] { let predicate: Predicate<Item> = #Predicate { item in tokens.contains { token in item.textString.contains(token) } } let descriptor = FetchDescriptor(predicate: predicate) return try context.fetch(descriptor) }
2
1
335
3w