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

224 Posts
Sort by:
Post not yet marked as solved
0 Replies
24 Views
How can we identify whether the remote change notification is triggered because some data was changed on a different device and it is downloaded from CloudKit, or it is triggered from the current device because new entity was saved into database. Because this notification is posted when both remote data is downloaded or local data is created. It would be great if there is a way to understand the origin of the notification.
Posted
by
Post not yet marked as solved
0 Replies
24 Views
I am using a Mac Catalyst app and saving the content of the app in core data. After uninstalling the app the saved core data file is not getting deleted. Due to this I am having major bugs during launch of the app. My requirement is core data contents should be removed once the app is uninstalled. Anybody with solutions for this?
Posted
by
Post not yet marked as solved
1 Replies
32 Views
Has anyone successfully persisted Color, particularly in SwiftData? So far my attempts have failed: Making Color conform to Codable results in a run time error (from memory something about ColorBox). Color.Resolved already conforms Codable but this results in "SwiftData/ModelCoders.swift:124: Fatal error: Composite Coder only supports Keyed Container" None of the other color types conform to Codable (CGColor, NSColor and UIColor) so does the swift language really not have a persistable color type?
Posted
by
Post not yet marked as solved
0 Replies
47 Views
CoreData: Zone metadata is missing it's encoded share data but is marked for a mutation: <CKRecordZoneID: 0x600003f044e0; zoneName=com.apple.coredata.cloudkit.share.30BE5FAE-3FE0-4142-90C4-E78FFA90B2A2, ownerName=defaultOwner> - <decode: bad range for [%@] got [offs:312 len:1242 within:0]>
Posted
by
Post not yet marked as solved
0 Replies
55 Views
Hello, I have class file, which should save data coreData and Im only able to save data via ui. Do you have any example, how can I save data in core data via class files? Greeting Fabian
Posted
by
Post not yet marked as solved
8 Replies
164 Views
Hi, I have been working on some kind of network filtering app for iOS using Content Filter Provider. And I have stored rules for each domain. As of right now, I use UserDefaults with my app's bundle suite to store and observe rules. I have also read this documentation page for UserDefaults link. Is it okay to use UserDefaults in my case, if I have rules added/modified dynamically as the flow is intercepted, or should I pick some other approach like Core Data, SwiftData, etc.? Thank you!
Posted
by
Post not yet marked as solved
0 Replies
86 Views
I am currently writing an app that is about writing stories. As of now, it is fairly simple: ContentView is your "Collection" of stories. PopupView is when you click on a button in ContentView. In popup view you enter the story title. Once you do that, you are brought to a blank page which is StoryView, where the NavigationTitle is what your story title is. Once I finish the story and leave the page / StoryView, it is still there, but once I close the app on my phone and reopen it, the story is gone and is not saved. I am a relatively new developer, so ive been relying on ChatGPT and Google Gemini for the saving parts of this, but it rarely works, and the furthest ive gotten with it is that it saves the story title but doesn't save the content of the story. I have a feeling that the AI is overdoing it as well. If anyone could help, please do so. Ive been trying to fix this for days. If you need me to provide any code, I am happy to do so. [Edited by Moderator]
Posted
by
Post not yet marked as solved
1 Replies
85 Views
Hello. I recently released a new version (2.6) of my CloudKit syncing CoreData based app. The new version uses v18 of my data model. V18 is exactly like v17, except for a new optional string field in one of the entities. I diffed the two model versions to be extra sure. During my test I did not encounter any crash, and I also tested automatic migration, installing 2.55 and building 2.6 on top of it. No troubles. However my crash logger reports a number of crashes among my users. It's not a huge numbers (10 users over about 900 or more) but I am surprised it crashes at all. The crash happens when I call NSPersistentCloudKitContainer.loadPersistentStores, I get this error in the completion block: The model used to open the store is incompatible with the one used to create the store" I always assumed these slight changes (new field added to an existing model) did not require a manual migration. Any suggestions?
Posted
by
Post not yet marked as solved
0 Replies
131 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
Post not yet marked as solved
0 Replies
142 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
Post not yet marked as solved
3 Replies
218 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
Post not yet marked as solved
1 Replies
212 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
Post marked as solved
2 Replies
194 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
Post not yet marked as solved
0 Replies
180 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
Post not yet marked as solved
0 Replies
173 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
Post not yet marked as solved
1 Replies
204 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
Post not yet marked as solved
1 Replies
198 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
Post not yet marked as solved
0 Replies
234 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