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.

Core Data Documentation

Posts under Core Data tag

232 Posts
Sort by:
Post not yet marked as solved
0 Replies
67 Views
We currently have a shoebox-based architecture but want to transition to a document-based architecture, so UIManagedDocument seems like an obvious choice. However, the UIManagedDocument API seems outdated given the relatively newer NSPersistentContainer API. Also, it’s not clear if UIManagedDocument’s managedObjectContext can be used on the main thread or not. Ideally, I would like to see a persistentContainer property added to UIManagedDocument which could then be used to obtain the view context or a background managed object context. Does anyone have any suggestions on the latest best practices for document-based architectures using CoreData? I’m more interested in Swift implementations, but knowing best practices for SwiftUI and SwiftData would be helpful too.
Posted
by yodeler.
Last updated
.
Post not yet marked as solved
4 Replies
352 Views
Hi all In pursuit of adopting widgets in my application, I have transitioned from AppSupport to AppGroup as storage location for Core Data. I have done a migration process/flow that goes as follows and which have been tested multiple times although I have yet to publish the update: Check if migration has taken place or not 1a. if yes continue to app 1b. If no continue flow Begin migration process 2a. Backup original store in AppSupport 2b. Migrate store to AppGroup 2c. Migrate userdefaults to AppGroup 2d. Update userdefaults with true for both hasMigratedToAppGroup and hasMigratedUserDefaultsToAppGroup Is there any tips or stuff to look for that hasn’t been taken in to account? How have you done it previously, and what would be recommended? Also, is there some specific tests to run/over many times get a baseline of how many is succeeding or failing? Thanks in advance.
Posted
by Aam1997.
Last updated
.
Post not yet marked as solved
0 Replies
64 Views
I am building an app that manages ScreenTime and I would like to persist the tokens of which apps are frequently limited to CoreData locally. I attempted to do so by converting to a string but was unable to find a way to initialize an ActivityCategoryToken with a string. Is this possible? Am I going about it the wrong way? Thanks.
Posted
by gweinz.
Last updated
.
Post not yet marked as solved
3 Replies
137 Views
What sets the SwiftData framework apart from traditional iOS data storage solutions like Core Data or Realm? Could you elaborate on SwiftData's unique features and architecture that enable developers to efficiently manage data in their Swift projects? How does SwiftData enhance the development experience by seamlessly integrating with Swift's language features and paradigms
Posted
by SULTAN_95.
Last updated
.
Post not yet marked as solved
1 Replies
154 Views
I recently discovered the new documentation for enabling CloudKit sync with SwiftData. A key step I was missing in my previous setup was this step: Initialize the CloudKit development schema. When I run this though, I get Core Data errors in my log... CoreData: Unsupported attribute type I've noticed that it seems to be preventing adding fields for my model properties that are Codable structs. I've been able to add Codable structs to my SwiftData models synced with CloudKit before. But using Core Data to initialize the CloudKit schema like the documentation suggests just doesn't work. Is there some other way around this? I'm about to just give up on CloudKit sync altogether. I need this to work because I'm trying to add some new fields and populate the fields with data based on existing data during the migration, but this seems to be preventing migration completely. If I don't initialize the schema, I get different errors and the ModelContainer won't initialize at all.
Posted
by jonduenas.
Last updated
.
Post marked as solved
2 Replies
135 Views
Some of my users are reporting an inability to sync via CloudKit between devices. I have not seen it on any of my devices, but one user got me some console logs that are showing the following error: <CKError 0x600000a0f840: "Partial Failure" (2/1011); "Failed to modify some records"; uuid = EDC7B3E3-02F8-43B7-83B6-22D17EF0442A; container ID = "iCloud.cribaudo.iphemeris"; partial errors: { C611E11F-3DC0-484C-8FC1-23473062D9D0:(com.apple.coredata.cloudkit.zone:defaultOwner) = <CKError 0x600000a04660: "Invalid Arguments" (12/2006); server message = "Cannot create or modify field 'CD_nameFirstChar' in record 'CD_Charts' in production schema"; op = D83EF1F7DD772042; uuid = EDC7B3E3-02F8-43B7-83B6-22D17EF0442A> I do not understand this: The field CD_nameFirstChar was added to the data model in the version 15. Automatic Migration is enabled. The CloudKit Console says the Private Database Container being used by my App is deployed to production. The entity CD_Charts (I only have one) that is deployed to production shows that field as present (CD_nameFirstChar). Why would this user be getting this error? As far as I can see they are running a version where migration to Model 15 should have been triggered at some point in the past. If somehow something went wrong with their migration, how would I fix it? Any thoughts / ideas are appreciated. One thing I should add is that the migration from Model 14 to 15 was not lightweight. I did use: @interface ModelMigration14to15 : NSEntityMigrationPolicy -(NSString *)nameFirstChar:(NSString *)name; @end And I used a MapModel14to15 which used the above function to set the value of nameFirstChar. The Value Expression for that attribute is: FUNCTION($entityPolicy,` "nameFirstChar:" , $source.name) from the above mentioned NSEntityMigrationPolicy class. This worked ok on all my devices and apparently on some user devices. This issues seems to effect only a small subset of my users but not all? So I am at a loss to understand why this would happen or how to fix it.
Posted
by cliffr.
Last updated
.
Post not yet marked as solved
0 Replies
112 Views
Porting some Core Data code that was written several years ago. It has an entity called Transaction. This pre-dates Transaction that appeared in Animation. So Apple is now colliding with my naming. Looks like light weight migration isn't going to do the trick and I need to do more work for migration to work. Checking whether there is some magical use of namespace where I could separate my entity use of Transaction. Or it's full weight migration...
Posted
by purple.
Last updated
.
Post not yet marked as solved
2 Replies
748 Views
Hi, I thought this should be quite easy and maybe I only have tomatoes on my eyes, but I cannot find out how to call an action when the user clicks the red button or use CMD-W to close the Preferences window (= Settings Scene). I use Core Data. In the Preferences, many data structures, which define my system, are changed. I learned, that you shouldn't save too often to avoid performance problems, so now I want to save the Core Data context when the user closes the Preferences window. I tried .onDisappear, onChange of focus etc. but this didn't work. How can I define an action? Any hints are welcome :-)
Posted
by h725.
Last updated
.
Post not yet marked as solved
0 Replies
118 Views
Hello I have a TestFlight tester getting a random repeated crash when the app is interacting with core data. Every time it crashes we get the call stack like below from line 6 stating -NSManagedObject _processRecentChanges. Searching for _sharedIMPL_setvfk_core it seems to indicate a multithreading issue but my managedObjectContext is initialized with main queue concurrency. - (NSManagedObjectContext *)managedObjectContext { if (managedObjectContext != nil) { return managedObjectContext; } NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator]; if (coordinator != nil) { managedObjectContext = [[NSManagedObjectContext alloc] initWithConcurrencyType: NSMainQueueConcurrencyType]; [managedObjectContext setPersistentStoreCoordinator:coordinator]; } return managedObjectContext; } When I pulled the cashpoint in to the Xcode project everything appears to be running on the main thread. I can't seem to find documentation on what might be causing the issue. Any pointers would be appreciated. The app is compiled on Xcode 15 targeting iOS 15. Users device is iOS 17.3.1.
Posted
by cjhuber.
Last updated
.
Post not yet marked as solved
1 Replies
156 Views
Here is my basic problem. The app itself builds without issue, but when I simulate I get the following log in the debug console. The app also force closes when the Save function is selected with these errors. The app is a simple form which saves the data to a CoreData entity. It will do more (full CRUD) later after I deal with this particular issue. I have checked and rechecked class names, spelling issues, case sensitivities. I can not seem to find the issue. error: No NSEntityDescription in any model claim the NSManagedObject subclass 'App.Entity' so +entity is confused. Have you loaded your NSManagedObject Model yet? Also: error: +[App.Entity entity] Failed to find a unique match for an NSEntityDescription to a managed object subclass
Posted
by AtreuIT.
Last updated
.
Post not yet marked as solved
2 Replies
314 Views
Hi, I am running into a reproducible SwiftUI List crash when using @FetchRequest based on an @ObservedObject. The crash happens only when deleting the last item in a section. All other deletes and inserts (that I've tested so far) seem to work fine. I'm hoping I can figure out why this happens, and if there is a workaround that I can use. The crash looks something like this: *** Assertion failure in -[SwiftUI.UpdateCoalescingCollectionView _endItemAnimationsWithInvalidationContext:tentativelyForReordering:animator:collectionViewAnimator:], UICollectionView.m:10643 *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'attempt to delete item 17 from section 0 which only contains 17 items before the update' The setup: I have a Core Data one-to-many relationship ... in this case, a Contact that has many Notes saved to it. When you select a Contact from a list, it goes to a ContactDetailsView which has some details of the contact, and a list of 'notes' saved to it. struct ContactDetailsView: View { @Environment(\.managedObjectContext) private var viewContext @ObservedObject var contact: Contact // -> making this 'let' works var body: some View { VStack (alignment: .leading) { Text(contact.firstName ?? "") Text(contact.lastName ?? "") NotesListView(contact: contact) Button("Add Test Notes") { let note1 = Notes(context: viewContext) note1.noteMonth = "Feb" note1.noteDetails = "Test1" note1.noteDate = Date() note1.contact = contact try? viewContext.save() } } .padding() } } The NotesListView has a @SectionedFetchRequest (the error is the same if I use a regular @FetchRequest). struct NotesListView: View { @Environment(\.managedObjectContext) private var viewContext @ObservedObject var contact: Contact // -> making this 'let' works @SectionedFetchRequest var sectionNotes: SectionedFetchResults<String, Notes> @State private var selectedNote: Notes? init(contact: Contact) { self.contact = contact let fetchRequest = Notes.fetchRequest() fetchRequest.predicate = NSPredicate(format: "contact == %@", contact) fetchRequest.sortDescriptors = [NSSortDescriptor(key: "noteDate", ascending: true)] _sectionNotes = SectionedFetchRequest(fetchRequest: fetchRequest, sectionIdentifier: \.noteMonth!) } var body: some View { List (selection: $selectedNote){ ForEach(sectionNotes) { section in Section(header: Text(section.id)) { ForEach(section, id: \.self) { note in VStack (alignment: .leading){ if let details = note.noteDetails { Text(details) } } .swipeActions { Button(role: .destructive, action: { delete(note: note) }, label: { Image(systemName: "trash") }) } } } } } } public func delete(note: Notes){ viewContext.delete(note) do{ try viewContext.save() } catch{ print("delete note error = \(error)") } } } Calling the delete method from swipe-to-delete always crashes when the note is the last item on the list. In the ContactDetailsView, and it's child view NotesListView I have marked the 'var contact: Contact' as an @ObservedObject. This is so that changes made to the contact can be reflected in the ContactDetailsView subviews (the name fields here, but there could be more). If I make both of these properties let contact: Contact, I don't get a crash anymore! But then I lose the 'observability' of the Contact, and changes to the name won't reflect on the Text fields. So it seems like something about @ObservedObject and using a List in its subviews is causing this problem, but I'm not sure why. Maybe the @ObservedObject first reloads its relationship and updates the view, and then the FetchRequest also reloads the List, causing a double-delete? But it surprisingly only happens for the last element in the list, and not otherwise. Another option I considered was losing the @FetchRequest and using contact.notes collection to drive the list. But isn't that inefficient compared to a @FetchRequest, especially with sorting and filtering, and loading the list of 1000s of notes? Any suggestions for a work-around are welcome. The full crash looks something like this: *** Assertion failure in -[SwiftUI.UpdateCoalescingCollectionView _endItemAnimationsWithInvalidationContext:tentativelyForReordering:animator:collectionViewAnimator:], UICollectionView.m:10643 *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'attempt to delete item 17 from section 0 which only contains 17 items before the update' *** First throw call stack: ( 0 CoreFoundation 0x0000000180491128 __exceptionPreprocess + 172 1 libobjc.A.dylib 0x000000018008412c objc_exception_throw + 56 2 Foundation 0x0000000180d1163c _userInfoForFileAndLine + 0 3 UIKitCore 0x0000000184a57664 -[UICollectionView _endItemAnimationsWithInvalidationContext:tentativelyForReordering:animator:collectionViewAnimator:] + 4020 4 UIKitCore 0x0000000184a62938 -[UICollectionView _performBatchUpdates:completion:invalidationContext:tentativelyForReordering:animator:animationHandler:] + 388 5 SwiftUI 0x00000001c51f0c88 OUTLINED_FUNCTION_249 + 5648 .... 39 TestCoreDataSwiftUISections 0x000000010248c85c $s27TestCoreDataSwiftUISections0abcdE3AppV5$mainyyFZ + 40 40 TestCoreDataSwiftUISections 0x000000010248c998 main + 12 41 dyld 0x0000000102625544 start_sim + 20 42 ??? 0x00000001027560e0 0x0 + 4336214240 43 ??? 0x2103000000000000 0x0 + 2378745028181753856
Posted
by zulfishah.
Last updated
.
Post not yet marked as solved
11 Replies
6.8k Views
Any insights on how to incorporate CloudKit (or CoreData) in the WidgetKit extension? Where in the WidgetKit api do I make the asynchronous call to load the data to be available for the TimelineProvider?
Posted
by cristosv.
Last updated
.
Post not yet marked as solved
1 Replies
146 Views
I have set a core data structure based on two entities : first entity is "Mot" (Word) with one String attribute "graphie" (spelling) and one ToOne relationship "definition" with the second entity. second entity is "Definition" that has one String attribute "enonce" (statement) and on ToMany relationship "mot" with entity Mot. One word can have several spellings but only one definition. I managed to load several rows of data and now, when I select one word I want to display all the spellings, which means all "Mot" that have the same definition. In my content view I have a List based on a request: @Environment(\.managedObjectContext) private var viewContext @FetchRequest(entity: Mot.entity(), sortDescriptors: [NSSortDescriptor(key: "graphie", ascending: true)]) private var mots: FetchedResults<Mot> var body: some View { NavigationView { ... List { ForEach(mots) { (mot: Mot) in HStack { Text(mot.graphie ?? "Non trouvé") Spacer() Text(mot.definition!.enonce ?? "Non trouvé") } .onTapGesture { motAffiche = mot tfMot = mot.graphie ?? "Not found" tfDefinition = mot.definition?.enonce ?? "Not found" tfOrthoAlt = returnOrthoAlt(mot: mot) } } } the function returnOrthoAlt(mot) is supposed to return a string with all spellings separated by commas. What is working for the moment, but not satisfactory is the following code for that function private func returnOrthoAlt(mot: Mot) -> String { var ort = [String]() for elem in mots { if elem.definition!.enonce! == mot.definition!.enonce! && elem != mot { ort.append(elem.graphie!) let defObjId = elem.definition!.objectID.uriRepresentation() print("\(elem.graphie!) def: \(elem.definition!.enonce!) \(defObjId) ") } } return if !ort.isEmpty { ort.joined(separator: ", ")} else {""} }: I am going through the table 'mots' of FetchedResults to find those that have the same definition as the current 'mot'. What I find not satisfactory is that I am comparing the 'mot.definition.enonce' of each Mot, which is not supposed to be unique, instead of 'mot.definition' directly, which did not work. The objects 'mot.definition' are obviously not equal (neither with == nor with === operators). Also I tried to retrieve the reverse relation directly with 'mot.definition.mot' but that returned a NSSet which, converted to a set seems to contain only one object, that is 'mot' itself. One possibility of course, would be to ad a unique Id to the entity 'Definition' but I seem to understand that this is not the recommended practice, the more so as swift does not provide system generated id. What do I miss in the core data concept ? Can someone help me out ?
Posted
by SimonWin.
Last updated
.
Post not yet marked as solved
0 Replies
182 Views
I want to display a list of 'contacts' in my app, loaded from a local Core Data sqlite database. Currently, I use UIKit, and with UITableView's cell reuse, even with 5000+ rows, the memory usage is great ... it loads at about 80MB and stays around that no matter how much I scroll up or down the list. I implemented the same list with SwiftUI List, and the memory usage while scrolling is very different ... the initial load is about the same, but each time I go down the whole list, it adds 20-30MB to the memory usage (according to Xcode). Is this a side-effect of using SwiftUI's List, or am I doing something wrong here? Here's the implementation: struct CJContactsListView: View { @SectionedFetchRequest var sectionContacts: SectionedFetchResults<String, Person> init() { let fetchRequest = Person.allContactsFetchRequest() _sectionContacts = SectionedFetchRequest(fetchRequest: fetchRequest, sectionIdentifier: \.normalizedSectionLetter!, animation: .default) } var body: some View { List { ForEach(sectionContacts) { section in Section(header: Text(section.id)) { ForEach(section) { person in CJContactsListLabelRowView(person: person) } } } } .listStyle(.plain) } } struct CJContactsListLabelRowView: View { @ObservedObject var person: Person var body: some View { HStack (alignment: .center, spacing: 8) { VStack (alignment: .leading){ if let displayName = person.displayName { Text(displayName).font(.headline) } if let companyName = person.companyName { Text(companyName).font(.subheadline).foregroundColor(.secondary) } } } } } extension Person: Identifiable { public var id: String { return self.objectID.uriRepresentation().absoluteString } public static func allContactsFetchRequest() -> NSFetchRequest<Person> { let request = Person.fetchRequest() request.sortDescriptors = Person.makeSortDescriptors() request.predicate = NSPredicate(format: "(isContactArchived == nil || isContactArchived == 0)") request.fetchBatchSize = 100 request.relationshipKeyPathsForPrefetching = ["tags"] return request } } There isn't a visible performance issue in my testing (i.e. I don't see a 'stutter' when scrolling really fast), but the memory profile growing does concern me, especially when this isn't a problem in UIKit. I've tested the "Earthquakes" sample project from Apple and it seems to display the same issue (memory profile grows substantially as the user scrolls down the list). Would love to know if there's a way to avoid this issue.
Posted
by zulfishah.
Last updated
.
Post not yet marked as solved
1 Replies
152 Views
Is there any app out there that lets you browse through a CoreData database? When I first started to learn Swift, an app called Liya seemed to work. But alas, no longer. it would just make it easier if there was anything out there that let you browse the data directly. Thanks
Posted
by SergioDCQ.
Last updated
.
Post marked as solved
1 Replies
253 Views
The Statement I have a SwiftUI app that uses CoreData and iCloud with NSPersistentCloudKitContainer prepared for beta testing via TestFlight. The app utilizes iCloud solely as a private database for user data across different devices. The app doesn't use any public or shared database. According to Apple's guidelines, deploying the development schema to production is necessary before submitting to the App Store: Before you publish your app, you must deploy the development schema to the production environment to copy over its record types, fields, and indexes. I am aware that once deployed to production, it's impossible to delete or modify any types or fields: To prevent conflicts, you can’t delete record types or fields that are already in production. Every time you deploy the development schema, its additive changes merge into the production schema. The Questions: When is the appropriate time to deploy the schema to production? Should it be done before beta testing via TestFlight, or is it sufficient to deploy it just before releasing the app on the App Store after beta testing? If the schema needs to be deployed before beta testing, does that mean I won't be able to reset the schema if testers discover critical bugs related to the data model, and I'll be compelled to delete or modify any types or fields? Thank you in advance for any responses!
Posted
by Hollycene.
Last updated
.
Post not yet marked as solved
3 Replies
560 Views
I'm trying to add two more data models SectionsSD andArticles SD to an existing project using SwiftData where I had one model and am running into a variety of CoreData errors when I try to run my app. I am running Xcode 15.2 and the latest iOS simulator at iOS 17.2 Here is my container let container: ModelContainer = { let schema = Schema([ LocationData.self, SectionsSD.self, ArticlesSD.self ]) let container = try! ModelContainer(for: schema, configurations: []) return container }() After I add these two models I get the following errors and I can't load data into the SectionsSD and ArticlesSD models. If I comment out my LocataionData model that works w/o error or if I run just LocationData it runs without error but run all together and I get the following errors in the log: error: Error: Persistent History (11) has to be truncated due to the following entities being removed: ( SectionsSD, ArticlesSD ) CoreData: error: Error: Persistent History (11) has to be truncated due to the following entities being removed: ( SectionsSD, ArticlesSD ) warning: Warning: Dropping Indexes for Persistent History CoreData: warning: Warning: Dropping Indexes for Persistent History warning: Warning: Dropping Transactions prior to 11 for Persistent History CoreData: warning: Warning: Dropping Transactions prior to 11 for Persistent History warning: Warning: Dropping Changes prior to TransactionID 11 for Persistent History Any advice here would be appreciated. These are initial models so migration is not really a need yet. Seems to just **** if you add more models.
Posted Last updated
.
Post not yet marked as solved
0 Replies
161 Views
In my recent endeavor, I aimed to introduce new Fetch Index Elements to the Core Data model of my iOS application. To achieve this, I followed a process of lightweight migration, detailed as follows: Navigate to Editor > Add Model Version to create a new version of the data model. Name the new version with a sequential identifier (e.g., MyAppModelV3.xcdatamodel) based on the naming convention of previous models. Select the newly created version, MyAppModelV3.xcdatamodel, as the active model. Mark this new version as the "Current" model in the Xcode properties panel on the right. In the new version of the model, MyAppModelV3.xcdatamodel, and add the new Fetch Index Elements there. Also, insert "v3" in the Versioning Hash Modifier field of affected entity, to indicate this modification. Upon reflection, I realized that creating a new version of the xcdatamodel might not have been necessary for this particular case. However, it appears to have caused no adverse effects on the application's functionality. During testing, I executed the application in a simulated environment, initially running an older version of the app to inspect the database content with SQLite DB Browser. I then upgraded to the latest app version to verify that the migration was successfully completed without causing any crashes. Throughout this testing phase, I employed the -com.apple.CoreData.MigrationDebug 1 flag to monitor all SQL operations, ensuring that indexes were appropriately dropped and recreated for the affected entity. Following thorough testing, I deployed the update to production. The majority of users were able to upgrade to the new app version seamlessly. However, a small fraction reported crashes at startup, indicated by the following error message: Fatal error: Unresolved error Error Domain=NSCocoaErrorDomain Code=134110 "An error occurred during persistent store migration." UserInfo={NSUnderlyingError=0x2820ad3e0 {Error Domain=NSCocoaErrorDomain Code=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." UserInfo={metadata={ NSPersistenceFrameworkVersion = 1338; NSStoreModelVersionChecksumKey = "qcPf6+DfpsPrDQ3j1EVXcBIrFe1O0R6IKd30sJf4IrI="; NSStoreModelVersionHashes = { NSAttachment = {length = 32, ... Strangely, the only way I could replicate this issue in the simulator was by running the latest version of the app followed by reverting to an older version, a scenario unlikely to occur in a real-world setting. This raises the question: How could this situation arise with actual users, considering they would typically move from an old to a new version rather than the reverse? I am reaching out to the community for insights or advice on this matter. Has anyone else encountered a similar problem during the Core Data migration process? How did you resolve it?
Posted
by yccheok.
Last updated
.