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

110 Posts

Post

Replies

Boosts

Views

Activity

Core Data Multiple NSEntityDescriptions claim the NSManagedObject subclass
Hello everyone, I'm trying to adopt the new Staged Migrations for Core Data and I keep running into an error that I haven't been able to resolve. The error messages are as follows: warning: Multiple NSEntityDescriptions claim the NSManagedObject subclass 'Movie' so +entity is unable to disambiguate. warning: 'Movie' (0x60000350d6b0) from NSManagedObjectModel (0x60000213a8a0) claims 'Movie'. error: +[Movie entity] Failed to find a unique match for an NSEntityDescription to a managed object subclass This happens for all of my entities when they are added/fetched. Movie is an abstract entity subclass, and it has the error error: +[Movie entity] Failed to find which is unique to the subclass entities, but this occurs for all entities. The NSPersistentContainer is loaded only once, and I set the following option after it's loaded: storeDescription.setOption( [stages], forKey: NSPersistentStoreStagedMigrationManagerOptionKey ) The warnings and errors only appear after I fetch or save to context. It happens regardless of whether the database was migrated or not. In my test project, using the generic NSManagedObject with NSEntityDescription.insertNewObject(forEntityName: "MyEntity", into: context) does not cause the issue. However, using the generic NSManagedObject is not a viable option for my app. Setting the module to "Current Project Module" doesn't change anything, except that it now prints "claims 'MyModule.Show'" in the warnings. I have verified that there are no other entities with the same name or renameIdentifier. Has anyone else encountered this issue, or can offer any suggestions on how to resolve it? Thanks in advance for any help!
4
0
113
Jun ’25
How to provide visual feedback about iCloud sync status when the user reinstalls an app?
It takes a few seconds, sometimes a few minutes for records to be downloaded back from CloudKit when the user reinstalls the app, which leads users to thinking their data was lost. I would like to know if there’s any way to provide a visual feedback about the current CloudKit sync status so I can let users know their data is being in fact downloaded back to their devices.
2
0
205
Mar ’25
Sync an interactive widget's Core Data store with the main app (and iCloud)
Hi everyone! I have an app on the App Store that uses Core Data as its data store. (It's called Count on Me: Tally Counter. Feel free to check it out.) One of the app's core feature is an interactive widget with a simple button. When the button is tapped, it's supposed to update the entity in the store. My requirement is that the changes are then reflected with minimal latency in the main app and – ideally – also on other devices of the same iCloud user. And vice-versa: When an entity is updated in the app (or on another device where the same iCloud user is logged in), the widget that shows this entity should also refresh to reflect the changes. I have read multiple articles, downloaded sample projects, searched Stackoverflow and the Apple developer forums, and tried to squeeze a solution out of AI, but couldn't figure out how to make this work reliably. So I tried to reduce the core problem to a minimal example project. It has two issues that I cannot resolve: When I update an entity in the app, the widget is immediately updated as intended (due to a call to WidgetCenter's reloadAllTimelines method). However, when I update the same entity from the interactive widget using the same app intent, the changes are not reflected in the main app. For the widget and the app to use the same local data store, I need to enable App Groups in both targets and set a custom location for the store within the shared app group. So I specify a custom URL for the NSPersistentStoreDescription when setting up the Core Data stack. The moment I do this, iCloud sync breaks. Issue no. 1 is far more important to me as I haven't officially enabled iCloud sync yet in my real app that's already on the App Store. But it would be wonderful to resolve issue no. 2 as well. Surely, there must be a way to synchronize changes to the source of truth triggered by interactive widget with other devices of the same iCloud user. Otherwise, the feature to talk to the main app and the feature to synchronize with iCloud would be mutually exclusive. Some other developers I talked to have suggested that the widget should only communicate proposed changes to the main app and once the main app is opened, it processes these changes and writes them to the NSPersistentCloudKitContainer which then synchronizes across devices. This is not an option for me as it would result in a stale state and potential data conflicts with different devices. For example, when a user has the same widget on their iPhone and their iPad, taps a button on the iPhone widget, that change would not be reflected on the iPad widget until the user decides to open the app on the iPhone. At the same time, the user could tap the button multiple times on their iPad widget, resulting in a conflicting state on both devices. Thus, this approach is not a viable solution. An answer to this question will be greatly appreciated. The whole code including the setup of the Core Data stack is included in the repository reference above. Thank you!
4
0
322
Apr ’25
How to Delete Tips from CloudKit?
Hi! I use Tips with CloudKit and it works very well, however when a user want to remove their data from CloudKit, how to do that? In CoreData with CloudKit area, NSPersistentCloudKitContainer have purgeObjectsAndRecordsInZone to delete both local managed objects and CloudKit records, however there is no information about the TipKit deletion. Does anyone know ideas?
2
0
394
Mar ’25
Crash during batch deletion merge when positive fractional decimals are stored and used in a derived attribute
I am experiencing a crash when performing a batch delete and merging changes on a Core Data store that uses NSPersistentCloudKitContainer. The crash appears to be triggered when positive fractional Decimal values are stored in a TransactionSplit entity (those values are aggregated via a derived attribute in the AccountTransaction entity). If I store whole numbers or negative fractional decimals, deletion seems to work correctly. I suspect that the issue is related to the internal representation of positive fractional decimals in conjunction with a derived attribute. Data Model Setup: Account (1:N relationship → AccountTransaction) AccountTransaction (1:N relationship → TransactionSplit), which contains a derived attribute (e.g., “splits.amount.@sum”) that computes the sum over the “amount” attribute on its related TransactionSplit objects. TransactionSplit, which contains a stored Decimal attribute named “amount” (of type Decimal/NSDecimalNumber). Steps to Reproduce: Insert sample data where each TransactionSplit’s “amount” is set to a positive fractional value (e.g., 1000.01), by using code similar to: func createSampleData() { // Execute all creation on the context’s queue. let checkingAccount = Account(context: context) checkingAccount.id = UUID() checkingAccount.name = "Main Checking" let randomTransactionCount = 1000 for _ in 0..<randomTransactionCount { let transaction = AccountTransaction(context: context) transaction.id = UUID() transaction.account = checkingAccount let randomValue = Double.random(in: 5...5000) let decimalValue = NSDecimalNumber(value: randomValue) let split1 = TransactionSplit(context: context) split1.id = UUID() split1.amount = decimalValue split1.transaction = transaction let split2 = TransactionSplit(context: context) split2.id = UUID() split2.amount = decimalValue split2.transaction = transaction } save() } The AccountTransaction’s derived attribute automatically aggregates the sum of its related TransactionSplit amounts. Perform a batch deletion using NSBatchDeleteRequest (with resultType set to .resultTypeObjectIDs) on your entities and merge the changes back into your main context: private func delete(_ fetchRequest: NSFetchRequest<NSFetchRequestResult>) { let batchDeleteRequest = NSBatchDeleteRequest(fetchRequest: fetchRequest) batchDeleteRequest.resultType = .resultTypeObjectIDs // ⚠️ When performing a batch delete we need to make sure we read the result back // then merge all the changes from that result back into our live view context // so that the two stay in sync. if let delete = try? context.execute(batchDeleteRequest) as? NSBatchDeleteResult { let changes = [NSDeletedObjectsKey: delete.result as? [NSManagedObjectID] ?? []] NSManagedObjectContext.mergeChanges(fromRemoteContextSave: changes, into: [context]) } } Save the context after deletion.
4
0
535
Mar ’25
dual predicate search using CoreData
I have a very simple CoreData model that has 1 entity and 2 attributes. This code works fine: .onChange(of: searchText) { _, text in evnts.nsPredicate = text.isEmpty ? nil :NSPredicate(format: "eventName CONTAINS %@ " , text ) but I'd like to also search with the same text string for my second attribute (which is a Date). I believe an OR is appropriate for two conditions (find either one). See attempted code below: evnts.nsPredicate = text.isEmpty ? nil : NSPredicate(format: "(eventName CONTAINS %@) OR (dueDate CONTAINS %i) " , text ) This crashes immediately %@ does the same. Is there a way to accomplish this? How is SwiftUI not an option below?
6
0
333
Mar ’25
Swift 6 Concurrency errors with ModelActor, or Core Data actors
In my app, I've been using ModelActors in SwiftData, and using actors with a custom executor in Core Data to create concurrency safe services. I have multiple actor services that relate to different data model components or features, each that have their own internally managed state (DocumentService, ImportService, etc). The problem I've ran into, is that I need to be able to use multiple of these services within another service, and those services need to share the same context. Swift 6 doesn't allow passing contexts across actors. The specific problem I have is that I need a master service that makes multiple unrelated changes without saving them to the main context until approved by the user. I've tried to find a solution in SwiftData and Core Data, but both have the same problem which is contexts are not sendable. Read the comments in the code to see the issue: /// This actor does multiple things without saving, until committed in SwiftData. @ModelActor actor DatabaseHelper { func commitChange() throws { try modelContext.save() } func makeChanges() async throws { // Do unrelated expensive tasks on the child context... // Next, use our item service let service = ItemService(modelContainer: SwiftDataStack.shared.container) let id = try await service.expensiveBackgroundTask(saveChanges: false) // Now that we've used the service, we need to access something the service created. // However, because the service created its own context and it was never saved, we can't access it. let itemFromService = context.fetch(id) // fails // We need to be able to access changes made from the service within this service, /// so instead I tried to create the service by passing the current service context, however that results in: // ERROR: Sending 'self.modelContext' risks causing data races let serviceFromContext = ItemService(context: modelContext) // Swift Data doesn't let you create child contexts, so the same context must be used in order to change data without saving. } } @ModelActor actor ItemService { init(context: ModelContext) { modelContainer = SwiftDataStack.shared.container modelExecutor = DefaultSerialModelExecutor(modelContext: context) } func expensiveBackgroundTask(saveChanges: Bool = true) async throws -> PersistentIdentifier? { // Do something expensive... return nil } } Core Data has the same problem: /// This actor does multiple things without saving, until committed in Core Data. actor CoreDataHelper { let parentContext: NSManagedObjectContext let context: NSManagedObjectContext /// In Core Data, I can create a child context from a background context. /// This lets you modify the context and save it without updating the main context. init(progress: Progress = Progress()) { parentContext = CoreDataStack.shared.newBackgroundContext() let childContext = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType) childContext.parent = parentContext self.context = childContext } /// To commit changes, save the parent context pushing them to the main context. func commitChange() async throws { // ERROR: Sending 'self.parentContext' risks causing data races try await parentContext.perform { try self.parentContext.save() } } func makeChanges() async throws { // Do unrelated expensive tasks on the child context... // As with the Swift Data example, I am unable to create a service that uses the current actors context from here. // ERROR: Sending 'self.context' risks causing data races let service = ItemService(context: self.context) } } Am I going about this wrong, or is there a solution to fix these errors? Some services are very large and have their own internal state. So it would be very difficult to merge all of them into a single service. I also am using Core Data, and SwiftData extensively so I need a solution for both. I seem to have trapped myself into a corner trying to make everything concurrency save, so any help would be appreciated!
6
0
793
Mar ’25
NSMigrationManager.migrateStore with NSPersistentHistoryTrackingKey
I am implementing a custom migration, and facing an issue while implementing a WAL checkpointing. Here is the code for WAL checkpointing func forceWALCheckpointingForStore(at storeURL: URL, model: NSManagedObjectModel) throws { let persistentStoreCoordinator = NSPersistentStoreCoordinator(managedObjectModel: model) let options = [NSSQLitePragmasOption: ["journal_mode": "DELETE"]] let store = try persistentStoreCoordinator.addPersistentStore(type: .sqlite, at: storeURL, options: options) try persistentStoreCoordinator.remove(store) } When the coordinator tries to add the store I am getting the following error fault: Store opened without NSPersistentHistoryTrackingKey but previously had been opened with NSPersistentHistoryTrackingKey - Forcing into Read Only mode store My questions are Is it really necessary to force WAL checkpointing before migration? I am expecting NSMigrationManager to handle it internally. I am assuming this because the migrateStore function asks for the sourceType where I am passing StoreType.sqlite If checkpointing is required, then how do I address the original issue Note: Since my app supports macOS 13, I am not able to use the newly introduced Staged migrations. There is similar question on Stackoverflow that remains unanswered. https://stackoverflow.com/q/69131577/1311902
6
0
592
Mar ’25
EXC_BAD_INSTRUCTION
public static func fetch(in context: NSManagedObjectContext, configurationBlock: (NSFetchRequest) -&amp;gt; () = { _ in }) -&amp;gt; [Self] { let request = NSFetchRequest(entityName: Self.entityName) configurationBlock(request) return try! context.fetch(request) } context.fetch(request), 'fetch' function has error. Thread 24: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)
7
0
731
Mar ’25
Crashes when trying to destroy persistent store
I am running into some issues when trying to destroy CoreData persistentStores. When a user logs out of my app, I want to completely reset CoreData and delete any existing data. My code to reset CoreData looks like this: let coordinator = self.persistentContainer.persistentStoreCoordinator self.persistentContainer.viewContext.reset() coordinator.persistentStores.forEach { store in guard let url = store.url else { return } do { try coordinator.destroyPersistentStore(at: url, type: .sqlite) _ = try coordinator.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: url) } catch { print(error) } } However, my app is crashing with Object 0xb2b5cc80445813de <x-coredata://BDB999D4-49A4-4CB3-AC3A-666AD60BEFC6/AccountEntity/p5> persistent store is not reachable from this NSManagedObjectContext's coordinator It seems this is related to the SwiftUI @FetchRequest wrappers. If I do not open the views where I am using @FetchRequest, the logout goes smoothly. Otherwise, I get the crash above. Has anyone run into anything similar? Is there something else I need to do to get the underlying FRC to release its references to those entities? I was under the impression that calling reset() on the managed object context would be enough to remove those items from memory and get the destroying of the persistent store to go smoothly. Alternately, is there another/better way I should be destroying the DB? Any advice or related observations would be greatly appreciated. Thank you!
2
0
642
Feb ’25
Core database relationship are only partially updating.
I created a data structure based on a dictionary of words. The purpose is to link each word to all other words made up of the same letters plus one. Example: table -> ablate, cablet, tabled, gablet, albeit, albite, etc. For this I built a data model made of three entities: Word, Draw, Link. A Draw is a set of letters corresponding to a Word and sorted in alphabetic order, like : HOUSE -> EHOSU. A Link is a letter that you add to a Draw to get another Draw. So my data model looks like this: And here is how I implemented it in Xcode: Entity Word (let's forget the attribute optComp that plays no role here) Entity Draw Entity Link I am populating the data in two steps: first I read a list of words from a .txt source and I populate the Word entity and at the same time the Draw entity with the corresponding relationship (function loadDic()) This first step apparently works fine. I can easily find all anagrams of any word with something like word.sort.word.spelling I read through the Draw entity. For each draw I seek all existing +1 draws considering each letter of the alphabet. If there are, I create a Link and add the relationships (function createLinks()) Here is where something goes wrong. If the Link's and the relationship Draw.plus seem to be correctly created, the other relationship Link.gives is only partially populated, say 50%. Moreover, I tried to apply an additional routine (updateLinks()) , focusing only on Link's with an empty Link.gives relationship and updating them. But again, only 50% of the nil relationships appear to be populated. I could not find out why those relationships are not properly populated. If someone can help me out I would be grateful. Here is the code: LoadDic() function (OK) : func loadDic() { print("Loading dictionary...") dataAlreadyLoaded.toggle() guard let url = Bundle.main.url(forResource: INPUT_FILE, withExtension: "txt") else { fatalError("\(INPUT_FILE).txt not found") } if let dico = try? String(contentsOf: url, encoding: String.Encoding.utf8 ) { let lines = dico.split(separator: "\r\n") for line in lines { let lineArray = line.split(separator: " ") print("\(lineArray[0])") // word let wordSorted = String(lineArray[0].sorted()) let draw = getDraw(drawLetters: wordSorted) ?? addDraw(drawLetters: wordSorted) // look if draw already exists, otherwise create new one. let wordItem = Word(context: viewContext) // create word entry with to-one-relationship to draw wordItem.spelling = String(lineArray[0]) wordItem.optComp = (Int(String(lineArray[1])) == 1) wordItem.sort = draw do { try viewContext.save() } catch { print("Errort saving ods9: \(error)") } } } print("Ods Chargé") } func addDraw(drawLetters: String) -> Draw { let newDraw = Draw(context: viewContext) newDraw.draw = drawLetters return(newDraw) } func getDraw(drawLetters: String) -> Draw? { let request: NSFetchRequest<Draw> = Draw.fetchRequest() request.entity = Draw.entity() request.predicate = NSPredicate(format: "draw == %@", drawLetters) do { let drw = try viewContext.fetch(request) return drw.isEmpty ? nil : drw[0] } catch { print("Erreur recherche Tirage") return nil } } createLinks() function (NOK): func createLinks() { var erreur = " fetch request <Draw>" let request: NSFetchRequest<Draw> = Draw.fetchRequest() request.entity = Draw.entity() request.predicate = NSPredicate(value: true) print("Building relationships...") do { let draws = try viewContext.fetch(request) count = draws.count for draw in draws { print("\(count) - \(draw.draw!)") linkTable.removeAll() for letter in ALPHABET { print(letter) let drawLettersPlus = String((draw.draw! + String(letter)).sorted()) // draw with one more letter if let drawPlus = draws.first(where: { $0.draw == drawLettersPlus }) { // look for Draw entity that matches augmented draw let linkItem = Link(context: viewContext) // if found, create new link based on letter with relationship to augmented draw linkItem.letter = String(letter) linkItem.gives = drawPlus erreur = " saving \(draw.draw!) + \(letter)" try viewContext.save() linkTable.append(linkItem) // saves link to populate the one-to-many relationship of the initial draw, once the alphabet is through } } let drawUpdate = draw as NSManagedObject // populate the one-to-many relationship of the initial draw let linkSet = Set(linkTable) as NSSet drawUpdate.setValue(linkSet, forKey: "plus") erreur = " saving \(draw.draw!) links plus" try viewContext.save() count -= 1 // next draw } } catch { print("Error " + erreur) } print("Graph completed") } updateLinks function (NOK): func updateLinks() { var erreur = "fetch request <Link>" let request: NSFetchRequest<Link> = Link.fetchRequest() request.entity = Link.entity() print("Running patch...") do { request.predicate = NSPredicate(format: "gives == nil") let links = try viewContext.fetch(request) for link in links { let baseDraw = link.back!.draw! print("\(baseDraw) \(link.letter!)") let augmDrawLetters = String((baseDraw + link.letter!).sorted()) if let augmDraw = getDraw(drawLetters: augmDrawLetters) { viewContext.perform { let updateLink = link as NSManagedObject updateLink.setValue(augmDraw, forKey: "gives") erreur = " saving \(augmDraw.draw!) \(link.letter!)" do { try viewContext.save() } catch { print("Erreur mise à jour lien") } } } } } catch { print("Error " + erreur) } } RESULT And this is the output showing the content of the Draw entity with relationships after createLinks() is applied: And here after updateLinks() is applied :
2
0
961
Feb ’25
Core Data Light Migration Crash When Widget is Installed (Error 134100)
I'm experiencing a crash during a lightweight Core Data migration when a widget that accesses the same database is installed. The migration fails with the following error: CoreData: error: addPersistentStoreWithType:configuration:URL:options:error: returned error NSCocoaErrorDomain (134100) error: userInfo: CoreData: error: userInfo: error: metadata : { NSPersistenceFrameworkVersion = 1414; NSStoreModelVersionChecksumKey = "dY78fBnnOm7gYtb+QT14GVGuEmVlvFSYrb9lWAOMCTs="; NSStoreModelVersionHashes = { Entity1 = { ... }; Entity2 = { ... }; Entity3 = { ... }; Entity4 = { ... }; Entity5 = { ... }; }; NSStoreModelVersionHashesDigest = "aOalpc6zSzr/VpduXuWLT8MLQFxSY4kHlBo/nuX0TVQ/EZ+MJ8ye76KYeSfmZStM38VkyeyiIPf4XHQTMZiH5g=="; NSStoreModelVersionHashesVersion = 3; NSStoreModelVersionIdentifiers = ( "" ); NSStoreType = SQLite; NSStoreUUID = "9AAA7AB7-18D4-4DE4-9B54-893D08FA7FC4"; "_NSAutoVacuumLevel" = 2; } The issue occurs only when the widget is installed. If I remove the widget’s access to the Core Data store, the migration completes successfully. The crash happens only once—after the app is restarted, everything works fine. This occurs even though I'm using lightweight migration, which should not require manual intervention. My suspicion is that simultaneous access to the Core Data store by both the main app and the widget during migration might be causing the issue. Has anyone encountered a similar issue? Is there a recommended way to ensure safe migration while still allowing the widget to access Core Data? Any insights or recommendations would be greatly appreciated.
3
0
696
Feb ’25
NSPersistentCloudKitContainer uploads only a subset of records to public database in production environment
I'm having some issues where only a subset of records appear in CloudKit dashboard after I have saved some records in my iOS app using NSPersistentCloudKitContainer. I have noticed that when I'm running my app using the development environment of my CloudKit container everything works smoothly and is uploaded as expected but when I'm using the production environment only a subset of records are actually uploaded. I'm pulling my hair on how to debug this. -com.apple.CoreData.CloudKitDebug and -com.apple.CoreData.SQLDebug pukes out too much info in the console for me to pinpoint any issue.
1
0
663
Feb ’25
Nested method calls in `context.perform` with Swift 6
I'm calling a method with the context as parameter, within the context's perform block – is this really not legal in Swift 6? actor MyActor { func bar(context: NSManagedObjectContext) { /* some code */ } func foo(context: NSManagedObjectContext) { context.performAndWait { self.bar(context: context) // WARN: Sending 'context' risks causing data races; this is an error in the Swift 6 language mode // 'self'-isolated 'context' is captured by a actor-isolated closure. actor-isolated uses in closure may race against later nonisolated uses // Access can happen concurrently } } } The warning appears when I call a method with a context parameter, within the performAndWait-block. Background: In my app I have methods that takes in API data, and I need to call the same methods from multiple places with the same context to store it, and I do not want to copy paste the code and have hundreds of lines of duplicate code. Is there a well-known "this is how you should do it" for situations like this? This is related to a previous post I made, but it's a bit flimsy and got no response: https://developer.apple.com/forums/thread/770605
1
1
858
Feb ’25
Mapping model not found if the attribute has "Preserve after deletion" enabled
I am trying to migrate my Core Data model to a new version with a new attribute added to it. Since my app supports macOS 13 I am not able to use the newly introduced Staged migrations. After much digging I found that the app is not able to find the Mapping Model when one of the attribute has "Preserve after deletion" enabled. I have enabled migration debbuging using com.apple.CoreData.MigrationDebug 1 I am getting following error error: CoreData: error: (migration) migration failed with error Error Domain=NSCocoaErrorDomain Code=134140 "Persistent store migration failed, missing mapping model." What is the way out here?
6
0
882
Feb ’25
Core Data Migration: Custom policy in Entity Mapping for the case where App name contains a space
I am trying to add a custom policy to Entity Mapping and it refuses to work because the app name has a space in it. I tried replacing the space character with underscore and hyphen but it still does not work. I tried creating an MVP where app name did not have any space and it worked in the first try. However, for another MVP where app name had a space in it, it is not working at all.
4
0
891
Feb ’25
CoreData error=134100 Failed to open the store
Hello, I'm using CoreData + CloudKit and I am facing the following error 134100 "The managed object model version used to open the persistent store is incompatible with the one that was used to create the persistent store." All my schema updates are composed of adding optional attributes to existing entities, adding non-optional attributes (with default value) to existing entities or adding new entities Basically, only things that lightweight migrations can handle. Every time I update the schema, I add a new model version of xcdatamodel - who only has a single configuration (the "Default" one). And I also deploy the updated CloudKit schema from the dashboard. It worked up to v3 of my xcdatamodel, but started to crash for a few users at v4 when I added 16 new attributes (in total) to 4 existing entities. Then again at v5 when I added 2 new optional attributes to 1 existing entity. I'm using a singleton and here is the code: private func generateCloudKitContainer() -> NSPersistentCloudKitContainer { let container = NSPersistentCloudKitContainer(name: "MyAppModel") let fileLocation = URL(...) let description = NSPersistentStoreDescription(url: fileLocation) description.shouldMigrateStoreAutomatically = true description.setOption(true as NSNumber, forKey: NSPersistentHistoryTrackingKey) description.setOption(true as NSNumber, forKey: NSPersistentStoreRemoteChangeNotificationPostOptionKey) let options = NSPersistentCloudKitContainerOptions(containerIdentifier: "iCloud.com.company.MyApp") options.databaseScope = .private description.cloudKitContainerOptions = options container.persistentStoreDescriptions = [description] container.viewContext.automaticallyMergesChangesFromParent = true container.loadPersistentStores { description, error in container.viewContext.mergePolicy = NSMergePolicy(merge: .mergeByPropertyObjectTrumpMergePolicyType) if let error { // Error happens here! } } return container } I can't reproduce it yet. I don't really understand what could lead to this error.
4
0
867
Feb ’25
NSFetchedResultsController index out of bounds during context merging changes
I've noticed several crashes that look like they're caused by an index out of bound in internal methods of NSFetchedResultsController. This happens while changes are merged from the persistent store container into the view context. Here's an example of the last exception backtrace. Exactly which internal methods that are called in - [NSFetchedResultsController(PrivateMethods) _core_managedObjectContextDidChange:] vary between crash reports but they all end up crashing from _NSArrayRaiseBoundException. The Core Data stack consists of one persistent store, one persistent store coordinator that the view context is set up to automatically merge changes from, and data is saved to disk from background context. persistentContainer.loadPersistentStores(...) viewContext = persistentContainer.viewContext viewContext.automaticallyMergesChangesFromParent = true backgroundContext = persistentContainer.newBackgroundContext() backgroundContext.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy backgroundClientContext = persistentContainer.newBackgroundContext() backgroundClientContext.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy Does anyone have any ideas what could be causing this? Thankful for any ideas or advice on how to investigate further.
2
0
710
Jan ’25
How to Resolve Core Data Composite Attributes Errors in Xcode?
How do I resolve these errors reported in Xcode about using Core Data Composite Attributes feature? Composite Attributes feature requires tvOS deployment target 17.0 or later Composite Attributes feature requires watchOS deployment target 10.0 or later My app is a Cocoa app and targets macOS 14.0+. I do not have an iOS, iPadOS, tvOS nor watchOS targets. So, I don't understand why I am getting these errors. My Xcode project format is set to Xcode 16.0. I am on macOS Sequoia 15.2 (24C101) and using Xcode Version 16.2 (16C5032a). If you create a new Xcode project and choose macOS > App and Storage > Core Data and then Add Composite Type and set an attribute name and type, you will get the errors.
3
0
513
Apr ’25