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

149 Posts
Sort by:

Post

Replies

Boosts

Views

Activity

CoreData crashing on iOS26
Hi, I work on a financial app in Brazil and since Beta 1 we're getting several crashes. We already opened a code level support and a few feedback issues, but haven't got any updates on that yet. We were able to resolve some crashes changing some of our implementation but we aren't able to understand what might be happening with this last one. This is the log we got on console: erro 11:55:41.805875-0300 MyApp CoreData: error: Failed to load NSManagedObjectModel with URL 'file:///private/var/containers/Bundle/Application/0B9F47D9-9B83-4CFF-8202-3718097C92AE/MyApp.app/ServerDrivenModel.momd/' We double checked and the momd is inside the bundle. The same app works on any other iOS version and if we build using Xcode directly (without archiving and installing on an iOS26 device) it works as expected. Have anyone else faced a similar error? Any tips or advice on how we can try to solve that?
1
2
70
1d
Core Data crash when used in widget extension
I have this very simple PersistenceController setup. It's used in both the main app and widget target. struct PersistenceController { static let shared = PersistenceController() @MainActor static let preview: PersistenceController = { let result = PersistenceController(inMemory: true) let viewContext = result.container.viewContext return result }() let container: NSPersistentContainer /// The main context. var context: NSManagedObjectContext { return container.viewContext } init(inMemory: Bool = false) { container = NSPersistentContainer(name: "Gamery") if inMemory { container.persistentStoreDescriptions.first!.url = URL(fileURLWithPath: "/dev/null") } else { do { let storeURL = try URL.storeURL(forAppGroup: "XXXXXXXXXX", databaseName: "Gamery") let storeDescription = NSPersistentStoreDescription(url: storeURL) /// Enable history tracking for cloud syncing purposes. storeDescription.setOption(true as NSNumber, forKey: NSPersistentHistoryTrackingKey) print("### Persistent container location: \(storeURL)") container.persistentStoreDescriptions = [storeDescription] } catch { print("Failed to retrieve store URL for app group: \(error)") } } container.loadPersistentStores(completionHandler: { (storeDescription, error) in if let error = error as NSError? { Crashlytics.crashlytics().record(error: error) fatalError("Unresolved error \(error), \(error.userInfo)") } }) container.viewContext.automaticallyMergesChangesFromParent = true container.viewContext.mergePolicy = NSMergePolicy.mergeByPropertyObjectTrump #if !WIDGET if !inMemory { do { try container.viewContext.setQueryGenerationFrom(.current) } catch { fatalError("###\(#function): Failed to pin viewContext to the current generation: \(error)") } } PersistentHistoryToken.loadToken() #endif } } I regularly receive crash logs from the widget. I never experienced crashes myself and the widgets work fine. GameryWidgetExtension/PersistenceController.swift:35: Fatal error: Unresolved error Error Domain=NSCocoaErrorDomain Code=256 "The file “Gamery.sqlite” couldn’t be opened." UserInfo={NSFilePath=/private/var/mobile/Containers/Shared/AppGroup/B6A63FE1-ADDC-4A4C-A065-163507E991C6/Gamery.sqlite, NSSQLiteErrorDomain=23}, ["NSSQLiteErrorDomain": 23, "NSFilePath": /private/var/mobile/Containers/Shared/AppGroup/B6A63FE1-ADDC-4A4C-A065-163507E991C6/Gamery.sqlite] I have absolutely no idea what's going on here. Anyone who can help with this?
1
1
62
3d
EXC_BAD_ACCESS When saving core data
I'm trying to convert some data, then save it back to Core Data. Sometimes this works fine without an issue, but occasionally I'll get an error Thread 1: EXC_BAD_ACCESS (code=1, address=0x0) It seems to occur when saving the core data context. I'm having trouble trying to debug it as it doesn't happen on the same object each time and can't reliably recreate the error Full view code can be found https://pastebin.com/d974V5Si but main functions below var body: some View { VStack { // Visual code here } .onAppear() { DispatchQueue.global(qos: .background).async { while (getHowManyProjectsToUpdate() > 0) { leftToUpdate = getHowManyProjectsToUpdate() updateLocal() } if getHowManyProjectsToUpdate() == 0 { while (getNumberOfFilesInDocumentsDirectory() > 0) { deleteImagesFromDocumentsDirectory() } if getNumberOfFilesInDocumentsDirectory() == 0 { DispatchQueue.main.asyncAfter(deadline: .now()) { withAnimation { self.isActive = true } } } } } } } update local function func updateLocal() { autoreleasepool { let fetchRequest: NSFetchRequest<Project> = Project.fetchRequest() fetchRequest.predicate = NSPredicate(format: "converted = %d", false) fetchRequest.fetchLimit = 1 fetchRequest.sortDescriptors = [NSSortDescriptor(keyPath: \Project.name, ascending: true), NSSortDescriptor(keyPath: \Project.name, ascending: true)] do { let projects = try viewContext.fetch(fetchRequest) for project in projects { currentPicNumber = 0 currentProjectName = project.name ?? "Error loading project" if let projectMain = project.mainPicture { currentProjectImage = getUIImage(picture: projectMain) } if let pictures = project.pictures { projectPicNumber = pictures.count // Get main image if let projectMain = project.mainPicture { if let imgThumbData = convertImageThumb(picture: projectMain) { project.mainPictureData = imgThumbData } } while (getTotalImagesToConvertForProject(project: project ) > 0) { convertImageBatch(project: project) } project.converted = true saveContext() viewContext.refreshAllObjects() } } } catch { print("Fetch Failed") } } } convertImageBatch function func convertImageBatch(project: Project) { autoreleasepool { let fetchRequestPic: NSFetchRequest<Picture> = Picture.fetchRequest() let projectPredicate = NSPredicate(format: "project = %@", project) let dataPredicate = NSPredicate(format: "pictureData == NULL") fetchRequestPic.predicate = NSCompoundPredicate(andPredicateWithSubpredicates: [projectPredicate, dataPredicate]) fetchRequestPic.fetchLimit = 5 fetchRequestPic.sortDescriptors = [NSSortDescriptor(keyPath: \Picture.dateTaken, ascending: true)] do { let pictures = try viewContext.fetch(fetchRequestPic) for picture in pictures { currentPicNumber = currentPicNumber + 1 if let imgData = convertImage(picture: picture), let imgThumbData = convertImageThumb(picture: picture) { // Save Converted picture.pictureData = imgData picture.pictureThumbnailData = imgThumbData // Save Image saveContext() viewContext.refreshAllObjects() } else { viewContext.delete(picture) saveContext() viewContext.refreshAllObjects() } } } catch { print("Fetch Failed") } } } And finally saving func saveContext() { do { try viewContext.save() } catch { let nsError = error as NSError fatalError("Unresolved error \(nsError), \(nsError.userInfo)") } }
6
0
124
1w
Sorting of FetchResults in TableView broken in xcode 26
Previously, I sorted my FetchResult in a TableView like this: @FetchRequest( sortDescriptors: [SortDescriptor(\.rechnungsDatum, order: .forward)], predicate: NSPredicate(format: "betragEingang == nil OR betragEingang == 0") ) private var verguetungsantraege: FetchedResults&lt;VerguetungsAntraege&gt; ... body ... Table(of:VerguetungsAntraege.self, sortOrder: $verguetungsantraege.sortDescriptors) { TableColumn("date", value:\.rechnungsDatum) { item in Text(Formatters.dateFormatter.string(from: item.rechnungsDatum ?? Date()) ) } .width(120) TableColumn("rechNrKurz", value:\.rechnungsNummer) { item in Text(item.rechnungsNummer ?? "") } .width(120) TableColumn("betrag", value:\.totalSum ) { Text(Formatters.currencyFormatter.string(from: $0.totalSum as NSNumber) ?? "kein Wert") } .width(120) TableColumn("klient") { Text(db.getKlientNameByUUID(id: $0.klient ?? UUID(), moc: moc)) } } rows: { ForEach(Array(verguetungsantraege)) { antrag in TableRow(antrag) } } There seem to be changes here in Xcode 26. In any case, I always get the error message in each line with TableColumn("title", value: \.sortingField) Ambiguous use of 'init(_:value:content:)' Does anyone have any idea what's changed? Unfortunately, the documentation doesn't provide any information.
0
0
101
1w
Prevent data loss from delayed schema deployment
Hi all, I recently discovered that I forgot to deploy my CloudKit schema changes from development to production - an oversight that unfortunately went unnoticed for 2.5 months. As a result, any data created during that time was never synced to iCloud and remains only in the local CoreData store. Once I pushed the schema to production, CloudKit resumed syncing new changes as expected. However, this leaves me with a gap: there's now a significant amount of data that would be lost if users delete or reinstall the app. Before I attempt to implement a manual backup or migration strategy, I was wondering: Does NSPersistentCloudKitContainer keep track of local changes that couldn't be synced doe to the missing schema and automatically reattempt syncing them now that the schema is live? If not, what would be the best approach to ensure this "orphaned" data gets saved to CloudKit retroactively. Thanks in advance for any guidance or suggestions.
0
0
96
2w
Crash with NSAttributedString in Core Data
I am trying out the new AttributedString binding with SwiftUI’s TextEditor in iOS26. I need to save this to a Core Data database. Core Data has no AttributedString type, so I set the type of the field to “Transformable”, give it a custom class of NSAttributedString, and set the transformer to NSSecureUnarchiveFromData When I try to save, I first convert the Swift AttributedString to NSAttributedString, and then save the context. Unfortunately I get this error when saving the context, and the save isn't persisted: CoreData: error: SQLCore dispatchRequest: exception handling request: <NSSQLSaveChangesRequestContext: 0x600003721140> , <shared NSSecureUnarchiveFromData transformer> threw while encoding a value. with userInfo of (null) Here's the code that tries to save the attributed string: struct AttributedDetailView: View { @ObservedObject var item: Item @State private var notesText = AttributedString() var body: some View { VStack { TextEditor(text: $notesText) .padding() .onChange(of: notesText) { item.attributedString = NSAttributedString(notesText) } } .onAppear { if let nsattributed = item.attributedString { notesText = AttributedString(nsattributed) } else { notesText = "" } } .task { item.attributedString = NSAttributedString(notesText) do { try item.managedObjectContext?.save() } catch { print("core data save error = \(error)") } } } }
2
0
63
2w
defaultIsolation option and Core Data
When creating a new project in Xcode 26, the default for defaultIsolation is MainActor. Core Data creates classes for each entity using code gen, but now those classes are also internally marked as MainActor, which causes issues when accessing managed object from a background thread like this. Is there a way to fix this warning or should Xcode actually mark these auto generated classes as nonisolated to make this better? Filed as FB13840800. nonisolated struct BackgroundDataHandler { @concurrent func saveItem() async throws { let context = await PersistenceController.shared.container.newBackgroundContext() try await context.perform { let newGame = Item(context: context) newGame.timestamp = Date.now // Main actor-isolated property 'timestamp' can not be mutated from a nonisolated context; this is an error in the Swift 6 language mode try context.save() } } } Turning code gen off inside the model and creating it manually, with the nonisolated keyword, gets rid of the warning and still works fine. So I guess the auto generated class could adopt this as well? public import Foundation public import CoreData public typealias ItemCoreDataClassSet = NSSet @objc(Item) nonisolated public class Item: NSManagedObject { }
1
0
58
3w
Core Data, Swift 6, Concurrency and more
I have the following struct doing some simple tasks, running a network request and then saving items to Core Data. Per Xcode 26's new default settings (onisolated(nonsending) & defaultIsolation set to MainActor), the struct and its functions run on the main actor, which works fine and I can even safely omit the context.perform call because of it, which is great. struct DataHandler { func importGames(withIDs ids: [Int]) async throws { ... let context = PersistenceController.shared.container.viewContext for game in games { let newGame = GYGame(context: context) newGame.id = UUID() } try context.save() } } Now, I want to run this in a background thread to increase performance and responsiveness. So I followed this session (https://developer.apple.com/videos/play/wwdc2025/270) and believe the solution is to mark the struct as nonisolated and the function itself as @concurrent. The function now works on a background thread, but I receive a crash: _dispatch_assert_queue_fail. This happens whether I wrap the Core Data calls with context.perform or not. Alongside that I get a few new warnings which I have no idea how to work around. So, what am I doing wrong here? What's the correct way to solve this simple use case with Swift 6's new concurrency stuff and the default main actor isolation in Xcode 26? Curiously enough, when setting onisolated(nonsending) to false & defaultIsolation to non isolating, mimicking the previous behavior, the function works without crashing. nonisolated struct DataHandler { @concurrent func importGames(withIDs ids: [Int]) async throws { ... let context = await PersistenceController.shared.container.newBackgroundContext() for game in games { let newGame = GYGame(context: context) newGame.id = UUID() // Main actor-isolated property 'id' can not be mutated from a nonisolated context; this is an error in the Swift 6 language mode } try context.save() } }
2
0
66
3w
NSPersistentCloudKitContainer causes crash on watchOS when device is offline
Hi. I'm hoping someone might be able to help us with an issue that's been affecting our standalone watchOS app for some time now. We've encountered consistent crashes on Apple Watch devices when the app enters the background while the device is offline (i.e., no Bluetooth and no Wi-Fi connection). Through extensive testing, we've isolated the problem to the use of NSPersistentCloudKitContainer. When we switch to NSPersistentContainer, the crashes no longer occur. Interestingly, this issue only affects our watchOS app. The same CloudKit-based persistence setup works reliably on our iOS and macOS apps, even when offline. This leads us to believe the issue may be specific to how NSPersistentCloudKitContainer behaves on watchOS when the device is disconnected from the network. We're targeting watchOS 10 and above. We're unsure if this is a misconfiguration on our end or a potential system-level issue, and we would greatly appreciate any insight or guidance.
2
0
63
3w
How to switch between Core Data Persistent Stores?
What is the best way to switch between Core Data Persistent Stores? My use case is that I have a multi-user app that stores thousands of data items unique to each user. To me, having Persistent Stores for each user seems like the best design to keep their data separate and private. (If anyone believes that storing the data for all users in one Persistent Store is a better design, I'd appreciate hearing from them.) Customers might switch users 5 to 10 times a day. Switching users must be fast, say a second or two at most.
1
0
50
2w
Crash with NSAttributedString in Core Data
I am trying out the new AttributedString binding with SwiftUI’s TextEditor in iOS26. I need to save this to a Core Data database. Core Data has no AttributedString type, so I set the type of the field to “Transformable”, give it a custom class of NSAttributedString, and set the transformer to NSSecureUnarchiveFromData When I try to save, I first convert the Swift AttributedString to NSAttributedString, and then save the context. Unfortunately I get this error when saving the context, and the save isn't persisted: CoreData: error: SQLCore dispatchRequest: exception handling request: <NSSQLSaveChangesRequestContext: 0x600003721140> , <shared NSSecureUnarchiveFromData transformer> threw while encoding a value. with userInfo of (null) Here's the code that tries to save the attributed string: struct AttributedDetailView: View { @ObservedObject var item: Item @State private var notesText = AttributedString() var body: some View { VStack { TextEditor(text: $notesText) .padding() .onChange(of: notesText) { item.attributedString = NSAttributedString(notesText) } } .onAppear { if let nsattributed = item.attributedString { notesText = AttributedString(nsattributed) } else { notesText = "" } } .task { item.attributedString = NSAttributedString(notesText) do { try item.managedObjectContext?.save() } catch { print("core data save error = \(error)") } } } } This is the attribute setup in the Core Data model editor: Is there a workaround for this? I filed FB17943846 if someone can take a look. Thanks.
2
0
139
2w
FoundationModels and Core Data
Hi, I have an app that uses Core Data to store user information and display it in various views. I want to know if it's possible to easily integrate this setup with FoundationModels to make it easier for the user to query and manipulate the information, and if so, how would I go about it? Can the model be pointed to the database schema file and the SQLite file sitting in the user's app group container to parse out the information needed? And/or should the NSManagedObjects be made @Generable for better output? Any guidance about this would be useful.
1
0
125
Jun ’25
Widget error upon restore iPhone: The file "Name.sqlite" couldn't be opened
I have an app that uses NSPersistentCloudKitContainer stored in a shared location via App Groups so my widget can fetch data to display. It works. But if you reset your iPhone and restore it from a backup, an error occurs: The file "Name.sqlite" couldn't be opened. I suspect this happens because the widget is created before the app's data is restored. Restarting the iPhone is the only way to fix it though, opening the app and reloading timelines does not. Anything I can do to fix that to not require turning it off and on again?
12
0
165
1w
No persistent stores error in SwiftData
I am following Apple's instruction to sync SwiftData with CloudKit. While initiating the ModelContainer, right after removing the store from Core Data, the error occurs: FAULT: NSInternalInconsistencyException: This NSPersistentStoreCoordinator has no persistent stores (unknown). It cannot perform a save operation.; (user info absent) I've tried removing default.store and its related files/folders before creating the ModelContainer with FileManager but it does not resolve the issue. Isn't it supposed to create a new store when the ModelContainer is initialized? I don't understand why this error occurs. Error disappears when I comment out the #if DEBUG block. Code: import CoreData import SwiftData import SwiftUI struct InitView: View { @Binding var modelContainer: ModelContainer? @Binding var isReady: Bool @State private var loadingDots = "" @State private var timer: Timer? var body: some View { VStack(spacing: 16) { Text("Loading\(loadingDots)") .font(.title2) .foregroundColor(.gray) } .padding() .onAppear { startAnimation() registerTransformers() let config = ModelConfiguration() let newContainer: ModelContainer do { #if DEBUG // Use an autorelease pool to make sure Swift deallocates the persistent // container before setting up the SwiftData stack. try autoreleasepool { let desc = NSPersistentStoreDescription(url: config.url) let opts = NSPersistentCloudKitContainerOptions(containerIdentifier: "iCloud.my-container-identifier") desc.cloudKitContainerOptions = opts // Load the store synchronously so it completes before initializing the // CloudKit schema. desc.shouldAddStoreAsynchronously = false if let mom = NSManagedObjectModel.makeManagedObjectModel(for: [Page.self]) { let container = NSPersistentCloudKitContainer(name: "Pages", managedObjectModel: mom) container.persistentStoreDescriptions = [desc] container.loadPersistentStores { _, err in if let err { fatalError(err.localizedDescription) } } // Initialize the CloudKit schema after the store finishes loading. try container.initializeCloudKitSchema() // Remove and unload the store from the persistent container. if let store = container.persistentStoreCoordinator.persistentStores.first { try container.persistentStoreCoordinator.remove(store) } } // let fileManager = FileManager.default // let sqliteURL = config.url // let urls: [URL] = [ // sqliteURL, // sqliteURL.deletingLastPathComponent().appendingPathComponent("default.store-shm"), // sqliteURL.deletingLastPathComponent().appendingPathComponent("default.store-wal"), // sqliteURL.deletingLastPathComponent().appendingPathComponent(".default_SUPPORT"), // sqliteURL.deletingLastPathComponent().appendingPathComponent("default_ckAssets") // ] // for url in urls { // try? fileManager.removeItem(at: url) // } } #endif newContainer = try ModelContainer(for: Page.self, configurations: config) // ERROR!!! } catch { fatalError(error.localizedDescription) } modelContainer = newContainer isReady = true } .onDisappear { stopAnimation() } } private func startAnimation() { timer = Timer.scheduledTimer( withTimeInterval: 0.5, repeats: true ) { _ in updateLoadingDots() } } private func stopAnimation() { timer?.invalidate() timer = nil } private func updateLoadingDots() { if loadingDots.count > 2 { loadingDots = "" } else { loadingDots += "." } } } import CoreData import SwiftData import SwiftUI @main struct MyApp: App { @State private var modelContainer: ModelContainer? @State private var isReady: Bool = false var body: some Scene { WindowGroup { if isReady, let modelContainer = modelContainer { ContentView() .modelContainer(modelContainer) } else { InitView(modelContainer: $modelContainer, isReady: $isReady) } } } }
2
0
103
May ’25
ForEach and RandomAccessCollection
I'm trying to build a custom FetchRequest that I can use outside a View. I've built the following ObservableFetchRequest class based on this article: https://augmentedcode.io/2023/04/03/nsfetchedresultscontroller-wrapper-for-swiftui-view-models @Observable @MainActor class ObservableFetchRequest&lt;Result: Storable&gt;: NSObject, @preconcurrency NSFetchedResultsControllerDelegate { private let controller: NSFetchedResultsController&lt;Result.E&gt; private var results: [Result] = [] init(context: NSManagedObjectContext = .default, predicate: NSPredicate? = Result.E.defaultPredicate(), sortDescriptors: [NSSortDescriptor] = Result.E.sortDescripors) { guard let request = Result.E.fetchRequest() as? NSFetchRequest&lt;Result.E&gt; else { fatalError("Failed to create fetch request for \(Result.self)") } request.predicate = predicate request.sortDescriptors = sortDescriptors controller = NSFetchedResultsController(fetchRequest: request, managedObjectContext: context, sectionNameKeyPath: nil, cacheName: nil) super.init() controller.delegate = self fetch() } private func fetch() { do { try controller.performFetch() refresh() } catch { fatalError("Failed to fetch results for \(Result.self)") } } private func refresh() { results = controller.fetchedObjects?.map { Result($0) } ?? [] } var predicate: NSPredicate? { get { controller.fetchRequest.predicate } set { controller.fetchRequest.predicate = newValue fetch() } } var sortDescriptors: [NSSortDescriptor] { get { controller.fetchRequest.sortDescriptors ?? [] } set { controller.fetchRequest.sortDescriptors = newValue.isEmpty ? nil : newValue fetch() } } internal func controllerDidChangeContent(_ controller: NSFetchedResultsController&lt;any NSFetchRequestResult&gt;) { refresh() } } Till this point, everything works fine. Then, I conformed my class to RandomAccessCollection, so I could use in a ForEach loop without having to access the results property. extension ObservableFetchRequest: @preconcurrency RandomAccessCollection, @preconcurrency MutableCollection { subscript(position: Index) -&gt; Result { get { results[position] } set { results[position] = newValue } } public var endIndex: Index { results.endIndex } public var indices: Indices { results.indices } public var startIndex: Index { results.startIndex } public func distance(from start: Index, to end: Index) -&gt; Int { results.distance(from: start, to: end) } public func index(_ i: Index, offsetBy distance: Int) -&gt; Index { results.index(i, offsetBy: distance) } public func index(_ i: Index, offsetBy distance: Int, limitedBy limit: Index) -&gt; Index? { results.index(i, offsetBy: distance, limitedBy: limit) } public func index(after i: Index) -&gt; Index { results.index(after: i) } public func index(before i: Index) -&gt; Index { results.index(before: i) } public typealias Element = Result public typealias Index = Int } The issue is, when I update the ObservableFetchRequest predicate while searching, it causes a Index out of range error in the Collection subscript because the ForEach loop (or a List loop) access a old version of the array when the item property is optional. List(request, selection: $selection) { item in VStack(alignment: .leading) { Text(item.content) if let information = item.information { // here's the issue, if I leave this out, everything works Text(information) .font(.callout) .foregroundStyle(.secondary) } } .tag(item.id) .contextMenu { if Item.self is Client.Type { Button("Editar") { openWindow(ClientView(client: item as! Client), id: item.id!) } } } } Is it some RandomAccessCollection issue or a SwiftUI bug?
0
0
60
May ’25
CoreData w/ Private and Shared Configurations
I have a CoreData model with two configuration - but several problems. Notably the viewContext only shows data from the .private configuration. Here is the setup: The private configuration holds entities, for example, User and Course and the shared one holds entities, for example, Player and League. I setup the NSPersistentStoreDescriptions to use the same container but with a databaseScope of .private/.shared and with the configuration of "Private"/"Shared". loadPersistentStores() does not report an error. If I try container.initializeCloudKitSchema() only the .private configuration produces CKRecord types. If I create a companion app using one configuration (w/ all entities) the schema initialization creates all CKRecord types AND I can populate some data in the .private and a created CKShare. I see that data in the CloudKit dashboard. If I axe the companion app and run the real thing w/ two configurations, the viewContext only has the .private data. Why? If when querying history I use NSPersistentHistoryTransaction.fetchRequest I get a nil return when using two configurations (but non-nil when using one).
0
0
43
Apr ’25
Cannot Find UI to Add Core Data Database Indexes in Xcode 16.2
Hi everyone, I'm trying to add standard, non-unique database indexes to my Core Data entities for performance optimization (e.g., indexing Date or String attributes used in predicates and sort descriptors). I'm using Xcode 16.2 on macOS Sequoia 15.1. My problem is that I cannot find the expected UI element in the Core Data model editor (.xcdatamodeld) to configure these database indexes. What I Understand / Expect: I know the old "Indexed" checkbox on the Attribute Inspector is deprecated/gone. My understanding from recent documentation and tutorials is that database indexing (separate from Spotlight indexing) should be configured in the Entity Inspector (when the Entity itself is selected), within a section titled "Indexes" (usually located below "Constraints"). This "Indexes" section should allow adding individual or compound indexes that translate to SQL CREATE INDEX commands, distinct from uniqueness constraints. What I'm Experiencing: When I select an Entity in the model editor, the "Indexes" section is completely missing from the Data Model Inspector pane on the right. I see sections for Name, Class, Constraints, Spotlight, User Info, Versioning, etc., but no "Indexes" section appears between Constraints and Spotlight (or anywhere else). Troubleshooting Steps Taken: Verified Selection: I have confirmed I am selecting the Entity itself in the left-hand list, not an individual Attribute. Ruled out Spotlight Indexing: I understand the difference between database indexing (for internal query performance) and the "Index in Spotlight" checkbox/Core Spotlight framework (for system search). I specifically need the former. Basic Xcode Troubleshooting: I have tried restarting Xcode, cleaning the build folder (Shift+Command+K), and deleting the project's Derived Data. The "Indexes" section remains missing. Checked File Placement/Target Membership: Confirmed the .xcdatamodeld file is correctly included in the target. Its location in the project navigator doesn't seem relevant. Checked Model Versioning: Ensured the correct model version is set as "Current" in the File Inspector. Ruled out Other Features: Confirmed that Fetch Requests, Fetched Properties, and User Info keys are not the mechanisms for defining database indexes. Confirmed Not Project-Specific: I created a brand new, template-generated iOS App project with "Use Core Data" checked. In this new project, when selecting the default "Item" entity, the "Indexes" section is also missing from the Entity Inspector. This strongly suggests the issue is with my Xcode environment/version itself, not my specific project's setup. Considered Programmatic/Manual: I understand Core Data expects schema definitions (including indexes) declaratively in the model file. While manual XML editing of the contents file works (adding ... within the tag), this is not the desired or intended workflow via the standard tools. My Questions: What is the correct, current procedure for defining non-unique Core Data database indexes using the Xcode UI in Xcode 16.2? Has the location or method for configuring database indexes changed in this version of Xcode? If so, where is it now? Is the absence of the "Indexes" section in the Entity Inspector a known issue or intentional change for this Xcode version? If the standard UI method is unavailable, what is the officially recommended approach (other than manual XML editing)? I've reviewed the documentation ("Configuring Entities", "Configuring Attributes") and while screenshots show the inspectors, they don't definitively show the "Indexes" section within the Entity Inspector, sometimes focusing on attributes or potentially being cropped. Any clarification or guidance would be greatly appreciated!
0
0
33
Apr ’25
Why Must All Attributes in a Composite Type Be Optional?
I recently encountered an issue involving Core Data’s new Composite Attributes feature and thought I would share my experience, as well as seek clarification. I created a composite type where all attributes were mandatory, except for one. Subsequently, I added an attribute to an entity and set its type to that composite type. Upon running the app, the console output the following error: CoreData: error: CoreData: error: Row (pk = 85) for entity ‘(EntityName)’ is missing mandatory text data for property ‘(propertyName)’ The way I resolved this was by removing the composite type attribute from the entity, after which the error no longer appeared. I also observed that in another entity, where a different composite type is used, all the attributes were optional — and no error occurred. This raises the question: why must all attributes in a composite type be optional? Furthermore, why does Xcode not inform the developer of this requirement? I have reviewed both the documentation and the WWDC23 “What’s New in Core Data” session, but neither mentions that having non-optional attributes within a composite type will cause such errors and lead to unpredictable application behaviour. Additionally, this issue remains unresolved in another area I raised previously in this topic: Composite Attributes feature requires tvOS deployment target 17.0 or later Composite Attributes feature requires watchOS deployment target 10.0 or later However, I do not have a tvOS or watchOS target, nor do I intend to add one. Could someone from Apple, or anyone with more experience, please clarify why all attributes within a composite type must be optional? And could it be possible for Xcode to flag this at compile time, rather than failing at runtime? Thank you in advance.
0
0
37
Apr ’25