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

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 } }
0
0
59
15h
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?
0
0
58
1d
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
89
4d
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
89
4d
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
163
1w
How does NSFetchRequest compare custom objects?
I have a CoreData-based app that's many years old, so it's been a long time since I've actually dealt with CoreData. Over recent years, I've noticed that fetch requests aren't finding the object I know is in there. The entity is called Folder and has a single attribute named url, which is of type Transformable. The transformer is a custom one that converts a url into a dictionary with 2 keys; one is a security scoped bookmark created from the url, and the other is the original url in case the bookmark fails. The dictionary is then converted to NSData using NSKeyedArchiver securely. The reverseTransformedValue does the opposite; unarchives the data to a dict, attempts to resolve the bookmark back into the url. The fetch request is set up to fetch all Folder objects where: Custom Predicate: url == $THE_URL So is the fetch request comparing the NSData that's stored in the file and comparing that to $THE_URL after running it through the transformer to arrive at an NSData, or is it running each one through the transformer to get the underlying url and comparing those with $THE_URL? Could there be a better way to compare urls in Core Data, when the app is sandboxed and must use security scoped bookmarks?
0
0
112
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
237
1w
UIDocument related hang in OS code
Hi A user of my app has contacted me about a crash they’re getting. They’ve sent me some logs (see attached) but I’m having difficulty working out what the cause is as it looks like it’s a watchdog timeout that’s occurring inside OS code, not my application. I also can’t reproduce the crash locally. App background info: The app logs peoples skydives, each log can contain a lot of data (rotation rates, acceleration, location, speeds, etc) and is stored in a separate file. These files can be stored in an iCloud container so the logs can be viewed from different devices. I use CoreData to maintain a database of key metadata so I can list the jumps in the UI even if the file for a jump isn’t on the device. Occasionally I have to delete this database and rebuild it by loading each jump log file and getting a fresh copy of the metadata. EG this can happen if a new version of the app requires an additional metadata field in the database. Crash info: The crash looks like it’s happening rebuilding the database, so the app will be trying to download and open each jump log and add the records to the database. I’ve noticed the following odd things about the crash log, which might be a good place to start: There’s a huge number of threads in the “”UIDocument File Access” dispatch queue that are blocked It looks like there's exactly 512 threads blocked in this queue. Which makes me think its hitting a limit. Any idea why they are blocked? I don’t know why there are so many, The database rebuild is done from an operation queue with a max concurrency of 10. So I would expect at most 10 jump logs to be being opened at one time There seams to be two common stack trace patterns. Eg compare thread 1 and thread 5 in crash log 1. In both crash logs the main thread is blocked, but in different bits of OS code in the two crash logs. It looks like this is the cause of the watchdog failure, but I’m not sure what the common cause could be. Any ideas / help would be really appreciated. Thanks Tom NOTE: I had to cut down the crash logs so they were small enough to upload. Crash log 1 small.txt Crash log 2 small.txt
0
0
128
2w
SwiftData crash: PersistentModel.keyPathToString(keypath:)
I'm distributing an iOS (17.4+) and visionOS (1.2+) app via TestFlight that's using SwiftData. The most common crash by far is from SwiftData when deleting models from a context using a predicate (first snippet below), but so far I've been unable to reproduce it myself locally (second snippet below). I'm using SwiftData outside of SwiftUI views, via my own wrapper, and converting between my app models and SwiftData models. Does anyone have any ideas how I could potentially narrow this issue down (or reproduce), or know of any similar issues? Thanks! — Seb do { try context.transaction { context in let predicate = #Predicate<PersistedFeed> { $0.id == id } do { try context.delete(model: PersistedFeed.self, where: predicate) } catch { // .. Omitted for brevity } } } catch { // .. Omitted for brevity } Crash: Thread 0 Crashed: 0 libswiftCore.dylib 0x000000018dd558c0 _assertionFailure(_:_:file:line:flags:) + 264 (AssertCommon.swift:144) 1 SwiftData 0x000000022f7f323c static PersistentModel.keyPathToString(keypath:) + 1496 (DataUtilities.swift:0) 2 SwiftData 0x000000022f83312c PredicateExpressions.KeyPath.convert(state:) + 492 (FetchDescriptor.swift:394) 3 SwiftData 0x000000022f834a24 protocol witness for ConvertibleExpression.convert(state:) in conformance PredicateExpressions.KeyPath<A, B> + 16 (<compiler-generated>:0) 4 SwiftData 0x000000022f830a70 PredicateExpression.convertToExpressionOrPredicate(state:) + 724 (FetchDescriptor.swift:203) 5 SwiftData 0x000000022f831874 PredicateExpression.convertToExpression(state:) + 36 (FetchDescriptor.swift:217) 6 SwiftData 0x000000022f83b6c8 PredicateExpressions.Equal.convert(state:) + 328 7 SwiftData 0x000000022f8360ec protocol witness for ConvertibleExpression.convert(state:) in conformance PredicateExpressions.Equal<A, B> + 64 (<compiler-generated>:0) 8 SwiftData 0x000000022f830a70 PredicateExpression.convertToExpressionOrPredicate(state:) + 724 (FetchDescriptor.swift:203) 9 SwiftData 0x000000022f82fd60 PredicateExpression.convertToPredicate(state:) + 28 (FetchDescriptor.swift:224) 10 SwiftData 0x000000022f82edb4 nsPredicate<A>(for:) + 956 (FetchDescriptor.swift:88) 11 SwiftData 0x000000022f807c2c ModelContext.delete<A>(model:where:includeSubclasses:) + 596 (ModelContext.swift:1846) 12 SwiftData 0x000000022f81994c dispatch thunk of ModelContext.delete<A>(model:where:includeSubclasses:) + 56
0
0
173
2w
Using NSFetchedResultsController with viewContext seems to have bad performance
Hello! Our team have been using a NSFetchedResultsController with viewContext for list UI. But we found some UI Hang logs, and I'm guessing that it happens because of Faulting in viewContext. The main thread call stacks in the logs look like below. 0 libsystem_kernel.dylib 0x00000001f378dbcc kevent_id + 8 1 libdispatch.dylib 0x00000001b4047b0f _dispatch_kq_poll + 227 2 libdispatch.dylib 0x00000001b40484df _dispatch_event_loop_wait_for_ownership + 435 3 libdispatch.dylib 0x00000001b4034983 __DISPATCH_WAIT_FOR_QUEUE__ + 339 4 libdispatch.dylib 0x00000001b403454b _dispatch_sync_f_slow + 147 5 CoreData 0x00000001b42859b3 _perform + 203 6 CoreData 0x00000001b4372767 -[NSManagedObjectContext+ 1275751 (_NestedContextSupport) newValuesForObjectWithID:withContext:error:] + 163 7 CoreData 0x00000001b424cf87 _PFFaultHandlerLookupRow + 275 8 CoreData 0x00000001b424cbbf _PF_FulfillDeferredFault + 191 9 CoreData 0x00000001b424cab7 _pvfk_header + 167 10 CoreData 0x00000001b424c9d7 _sharedIMPL_pvfk_core + 31 11 Works 0x000000010445517b closure #1 in static MailUIMailFactory.make(mail:needFolderName:) + 26530171 (MailUIMailFactory.swift:109) ... 0 libsystem_kernel.dylib 0x00000001dbd4254c kevent_id + 8 1 libdispatch.dylib 0x000000019b7057d3 _dispatch_kq_poll + 227 2 libdispatch.dylib 0x000000019b7061bb _dispatch_event_loop_wait_for_ownership + 435 3 libdispatch.dylib 0x000000019b6f2593 __DISPATCH_WAIT_FOR_QUEUE__ + 339 4 libdispatch.dylib 0x000000019b6f215b _dispatch_sync_f_slow + 147 5 CoreData 0x000000019b94f24b _perform + 203 6 CoreData 0x000000019ba3c41b -[NSManagedObjectContext+ 1274907 (_NestedContextSupport) newValueForRelationship:forObjectWithID:withContext:error:] + 167 7 CoreData 0x000000019b914387 -[NSFaultHandler retainedFulfillAggregateFaultForObject:andRelationship:withContext:] + 391 8 CoreData 0x000000019b9118bf -[_NSFaultingMutableSet willReadWithContents:] + 391 9 CoreData 0x000000019b91e663 -[_NSFaultingMutableSet count] + 23 10 Foundation 0x0000000192dbeb3f -[NSSet+ 7609151 (NSKeyValueSorting) sortedArrayUsingDescriptors:] + 55 11 Works 0x000000010249ec1f specialized static MailUIMailFactory.make(mail:needFolderName:) + 27470879 (MailUIMailFactory.swift:102) ... We just use NSFetchedResultsController's fetchedObjects in table view's cellForRowAt method, and make a new model by MailUIMailFactory.make. So we're thinking that we need to initialize NSFetchedResultsController with bg Context. What you guys think? Do I avoid using viewContext in heavy UI?
0
0
152
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
342
1w
How to embed SwiftData model container in a custom file package document type
Hi all, I have done a lot of research on this but am not able to come up with a workable solution. Background: I am trying to make an universal app on macOS/iOS that organizes media (image/video/pdf); think of its functionality like Apple's Photos app. So for my app document type, I would have my custom file package and within the package folder, there would be a SwiftData model container file and folders to hold user media. Approaches taken: DocumentGroup with SwiftData model then write directly into the file package In my App scene, I create document by having DocumentGroup(editing: .customDocument, migrationPlan: CustomMigrationPlan.self). This will create a document with a model container with my SwiftData model. And when I need to add media files into the document, I get the URL of the document, then use FileManager to write the file into the desired folder in the document. The result is that the media file is saved in the file package but then the SwiftData container is corrupted (all model data is reset to empty.) I am now trying to: 2. DocumentGroup with custom file package then try to embed SwiftData container In my current approach, I would create a document by having DocumentGroup(newDocument: CustomFileDocument()). I have custom FileDocument and FileWrapper. But the problem is I don't know how to embed a SwiftData container into my FileDocument. Is it possible to create a SwiftData model container when my FilerWrapper initialize? I can't figure out how to do this. Can anyone please advice on how I should accomplish this? Or if maybe I am looking at this problem wrongly? Do I need to use AppKit/UIKit with Core Data because it's currently not possible with SwiftUI/SwiftData? Thank you so much for reading and any input is greatly appreciated.
0
0
166
3w
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
244
1w
Prevent Data Retention in Core Data When View is Dismissed
Prerequisite Information I am trying to use Core Data in my SwiftUI app. I have created 3 entities, a Record, a Header and an Entry. The Record contains the Header entities. The Header contain other Header or Entry entities. The Entry has a title and a value. My List view looks like this, I fetch the records with a @FetchRequest. NavigationView { List { ForEach(records) { record in NavigationLink(destination: DetailView(headers: record.headers!.allObjects as? [Header] ?? [], isNewEntry: true)) { Text(record.id!.uuidString) } } } } In my DetailView I have a form that passes the details to other views which create a DisclosureGroup for a Header, a bold Text for a subheader, and a TextField for an Entry let headers: [Header] let isNewEntry: Bool @Environment(\.managedObjectContext) var managedObjectContext init(headers: [Header], isNewEntry: Bool = false) { self.headers = headers self.isNewEntry = isNewEntry } Form { ForEach(Array(headers.enumerated()), id: \.element) { index, header in HeaderView(header: header, isExpanded: Binding( get: { self.expandedStates[header.id!, default: false] }, set: { self.expandedStates[header.id!] = $0 } )) } } Problem When I press the record in the list, it takes me to the DetailView where I can write something in the TextField. Then if I slide back and do not press the save button and then press the same record again from the list, it retains the data I wrote in the TextField. Question How can I make it so that the data is not retained if I slide back except only when I press the save button? Please let me know if any other information is needed or if something is unclear.
0
1
201
3w
Can the NSPersistentCloudKitContainer mirror the data from the cloudKit public database to the local Core Data if the user is not logged in?
I'm currently syncing Core Data with the CloudKit public database using NSPersistentCloudKitContainer. The app starts with an empty Core Data store locally and at the app launch it downloads the data from CloudKit public database to the Core Data store, but this can only be accomplished if the user is logged in, if the user is not logged, no data gets downloaded and I get the error below. Can the NSPersistentCloudKitContainer mirror the data from the CloudKit public database to the local Core Data even if the user is not logged in? Can someone please confirm this is possible? The reason for my question is because I was under the impression that the users didn't need to be logged to read data from the public database in CloudKit but I'm not sure this applies to NSPersistentCloudKitContainer when mirroring data. I know I can fetch data directly with CloudKit APIs without the user beign logged but I need to understand if NSPersistentCloudKitContainer should in theory work without the user being logged. I hope someone from Apple sees this question since I have spent too much time researching without any luck. Error Error fetching user record ID: <CKError 0x600000cb1b00: "Not Authenticated" (9); "No iCloud account is configured"> CoreData: error: CoreData+CloudKit: -[NSCloudKitMirroringDelegate _performSetupRequest:]_block_invoke(1192): <NSCloudKitMirroringDelegate: 0x600003b00460>: Failed to set up CloudKit integration for store: <NSSQLCore: 0x10700f0d0> (URL: file:///Users/UserName/...
4
0
288
3w
NSFetchedResultsController - NSInvalidArgumentException
Good morning, I've developed an application where we download a JSON of objects and we store those information on a CoreData table. We've also created a Collection view used to show those information through a NSFetchedResultsController. Can someone helps me to understand the reason why I get this issue? Thanks indeed Fatal Exception: NSInvalidArgumentException 0 CoreFoundation 0x83f20 __exceptionPreprocess 1 libobjc.A.dylib 0x16018 objc_exception_throw 2 CoreFoundation 0x1b6250 _NSArrayRaiseInsertNilException 3 CoreFoundation 0x16f5c -[__NSCFArray objectAtIndex:] 4 CoreData 0x13af14 -[_PFMutableProxyArray subarrayWithRange:] 5 CoreData 0xc4948 -[_NSDefaultSectionInfo objects] 6 CoreData 0x9c3fc -[NSFetchedResultsController _conditionallyDispatchSnapshotToDelegate:updatesInfo:] 7 CoreData 0x6d4ec __82-[NSFetchedResultsController(PrivateMethods) _core_managedObjectContextDidChange:]_block_invoke 8 CoreData 0x270dc developerSubmittedBlockToNSManagedObjectContextPerform 9 CoreData 0x9d0ec -[NSManagedObjectContext performBlockAndWait:] 10 CoreData 0x9c6e8 -[NSFetchedResultsController _core_managedObjectContextDidChange:] 11 CoreFoundation 0x5178c __CFNOTIFICATIONCENTER_IS_CALLING_OUT_TO_AN_OBSERVER__ 12 CoreFoundation 0x516a8 ___CFXRegistrationPost_block_invoke 13 CoreFoundation 0x515f0 _CFXRegistrationPost 14 CoreFoundation 0x4fbb8 _CFXNotificationPost 15 Foundation 0x31574 -[NSNotificationCenter postNotificationName:object:userInfo:] 16 CoreData 0x6a548 -[NSManagedObjectContext _createAndPostChangeNotification:deletions:updates:refreshes:deferrals:wasMerge:] 17 CoreData 0x69d10 -[NSManagedObjectContext _postRefreshedObjectsNotificationAndClearList] 18 CoreData 0x68a4c -[NSManagedObjectContext _processRecentChanges:] 19 CoreData 0x91494 -[NSManagedObjectContext _coreMergeChangesFromDidSaveDictionary:usingObjectIDs:withClientQueryGeneration:] 20 CoreData 0x90334 -[NSManagedObjectContext mergeChangesFromContextDidSaveNotification:] 21 CoreData 0x270dc developerSubmittedBlockToNSManagedObjectContextPerform 22 libdispatch.dylib 0x3dd4 _dispatch_client_callout 23 libdispatch.dylib 0x125a4 _dispatch_main_queue_drain 24 libdispatch.dylib 0x121b8 _dispatch_main_queue_callback_4CF 25 CoreFoundation 0x56710 __CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE__ 26 CoreFoundation 0x53914 __CFRunLoopRun 27 CoreFoundation 0x52cd8 CFRunLoopRunSpecific 28 GraphicsServices 0x11a8 GSEventRunModal 29 UIKitCore 0x40a90c -[UIApplication _run] 30 UIKitCore 0x4be9d0 UIApplicationMain 31 Rainbow 0x80c0 main + 15 (main.swift:15) 32 ??? 0x1b3419e4c (Mancante)
1
0
200
3w
Crash: NSFetchedResultsController NSInvalidArgumentException
Good morning, I've developed an application in order to show the information stored into a CoraData Table on a CollectionView through a NSFetchedResultsController. Several times I got this issue, is there anyone who can help me to understand the reason why this happens? Thanks indeed. Fatal Exception: NSInvalidArgumentException 0 CoreFoundation 0x83f20 __exceptionPreprocess 1 libobjc.A.dylib 0x16018 objc_exception_throw 2 CoreFoundation 0x1b6250 _NSArrayRaiseInsertNilException 3 CoreFoundation 0x16f5c -[__NSCFArray objectAtIndex:] 4 CoreData 0x13af14 -[_PFMutableProxyArray subarrayWithRange:] 5 CoreData 0xc4948 -[_NSDefaultSectionInfo objects] 6 CoreData 0x9c3fc -[NSFetchedResultsController _conditionallyDispatchSnapshotToDelegate:updatesInfo:] 7 CoreData 0x6d4ec __82-[NSFetchedResultsController(PrivateMethods) _core_managedObjectContextDidChange:]_block_invoke 8 CoreData 0x270dc developerSubmittedBlockToNSManagedObjectContextPerform 9 CoreData 0x9d0ec -[NSManagedObjectContext performBlockAndWait:] 10 CoreData 0x9c6e8 -[NSFetchedResultsController _core_managedObjectContextDidChange:] 11 CoreFoundation 0x5178c CFNOTIFICATIONCENTER_IS_CALLING_OUT_TO_AN_OBSERVER 12 CoreFoundation 0x516a8 ___CFXRegistrationPost_block_invoke 13 CoreFoundation 0x515f0 _CFXRegistrationPost 14 CoreFoundation 0x4fbb8 _CFXNotificationPost 15 Foundation 0x31574 -[NSNotificationCenter postNotificationName:object:userInfo:] 16 CoreData 0x6a548 -[NSManagedObjectContext _createAndPostChangeNotification:deletions:updates:refreshes:deferrals:wasMerge:] 17 CoreData 0x69d10 -[NSManagedObjectContext _postRefreshedObjectsNotificationAndClearList] 18 CoreData 0x68a4c -[NSManagedObjectContext _processRecentChanges:] 19 CoreData 0x91494 -[NSManagedObjectContext _coreMergeChangesFromDidSaveDictionary:usingObjectIDs:withClientQueryGeneration:] 20 CoreData 0x90334 -[NSManagedObjectContext mergeChangesFromContextDidSaveNotification:] 21 CoreData 0x270dc developerSubmittedBlockToNSManagedObjectContextPerform 22 libdispatch.dylib 0x3dd4 _dispatch_client_callout 23 libdispatch.dylib 0x125a4 _dispatch_main_queue_drain 24 libdispatch.dylib 0x121b8 _dispatch_main_queue_callback_4CF 25 CoreFoundation 0x56710 CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE 26 CoreFoundation 0x53914 __CFRunLoopRun 27 CoreFoundation 0x52cd8 CFRunLoopRunSpecific 28 GraphicsServices 0x11a8 GSEventRunModal 29 UIKitCore 0x40a90c -[UIApplication _run] 30 UIKitCore 0x4be9d0 UIApplicationMain 31 Cloud 0x80c0 main + 15 (main.swift:15) 32 ??? 0x1b3419e4c (Mancante)
0
0
149
3w
Understanding Syncing between Core Data and CloudKit Public Database using NSPersistantCloudKitContainer
Can someone please give me an overview of how sync works between Core Data and the public CloudKit database when using the NSPersistentCloudKitContainer and please point out my misunderstandings based on what I describe below? In the following code, I'm successfully connecting to the public database in CloudKit using the NSPersistentCloudKitContainer. Below is how I have Core Data and CloudKit set up for your reference. In CloudKit I have a set of PublicIconImage that I created manually via the CloudKit Console. I intend to be able to download all images from the public database at the app launch to the local device and manage them via Core Data to minimize server requests, which works but only if the user is logged in. This is the behavior I see: When the app launches, all the CloudKit images get mirrored to Core Data and displayed on the screen but only if the user is logged in with the Apple ID, otherwise nothing gets mirrored. What I was expecting: I was under the impression that when connecting to the public database in CloudKit you didn't need to be logged in to read data. Now, if the user is logged in on the first launch, all data is successfully mirrored to Core Data, but then if the user logs off, all data previously mirrored gets removed from Core Data, and I was under the impression that since Core Data had the data already locally, it would keep the data already downloaded regardless if it can connect to CloudKit or not. What am I doing wrong? Core Data Model: Entity: PublicIconImage Attributes: id (UUID), imageName (String), image (Binary Data). CloudKit Schema in Public Database: Record: CD_PublicIconImage Fields: CD_id (String), CD_imageName (String), CD_image (Bytes). Core Data Manager class CoreDataManager: ObservableObject{ // Singleton static let instance = CoreDataManager() private let queue = DispatchQueue(label: "CoreDataManagerQueue") private var iCloudSync = true lazy var context: NSManagedObjectContext = { return container.viewContext }() lazy var container: NSPersistentContainer = { return setupContainer() }() func updateCloudKitContainer() { queue.sync { container = setupContainer() } } func setupContainer()->NSPersistentContainer{ let container = NSPersistentCloudKitContainer(name: "CoreDataContainer") guard let description = container.persistentStoreDescriptions.first else{ fatalError("###\(#function): Failed to retrieve a persistent store description.") } description.setOption(true as NSNumber, forKey: NSPersistentHistoryTrackingKey) let cloudKitContainerIdentifier = "iCloud.com.example.PublicDatabaseTest" let options = NSPersistentCloudKitContainerOptions(containerIdentifier: cloudKitContainerIdentifier) description.cloudKitContainerOptions = options description.cloudKitContainerOptions?.databaseScope = .public // Specify Public Database 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() }catch let error{ print("Error saving Core Data. \(error.localizedDescription)") } } } View Model Class class PublicIconImageViewModel: ObservableObject { let manager: CoreDataManager @Published var publicIcons: [PublicIconImage] = [] init(coreDataManager: CoreDataManager = .instance) { self.manager = coreDataManager loadPublicIcons() } func loadPublicIcons() { let request = NSFetchRequest<PublicIconImage>(entityName: "PublicIconImage") let sort = NSSortDescriptor(keyPath: \PublicIconImage.imageName, ascending: true) request.sortDescriptors = [sort] do { publicIcons = try manager.context.fetch(request) } catch let error { print("Error fetching PublicIconImages. \(error.localizedDescription)") } } } SwiftUI View struct ContentView: View { @EnvironmentObject private var publicIconViewModel: PublicIconImageViewModel var body: some View { VStack { List { ForEach(publicIconViewModel.publicIcons) { icon in HStack{ Text(icon.imageName ?? "unknown name") Spacer() if let iconImageData = icon.image, let uiImage = UIImage(data: iconImageData) { Image(uiImage: uiImage) .resizable() .aspectRatio(contentMode: .fit) .frame(width: 35, height: 35) } } } } .onAppear { // give some time to get the images downlaoded DispatchQueue.main.asyncAfter(deadline: .now() + 5){ publicIconViewModel.loadPublicIcons() } } } .padding() } }
0
0
180
4w