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

358 Posts
Sort by:
Post not yet marked as solved
1 Replies
108 Views
So this project is pretty straightforward. I have an item. The use can create, get a closer look at, delete, or edit an item. For some reason, no matter how many different ways I try to do it, the edit part does not work. I've tried moving the sheet outside of the context menu (it only opens the bottom item), I've tried moving it under the list using the first index of the item (it crashes), and finally I've tried it the shown way and it just doesn't do anything. If anyone can come up with a better way to open the edit view for the correct item (preferably using a context menu, but something similar is acceptable) I would really appreciate it. I've provided the project for a better understanding of what I'm trying to do. If you have any questions just leave a comment. Any help would be greatly appreciated. Content View: struct ContentView: View {     @Environment(\.managedObjectContext) var managedObjContext     @ObservedObject var persistence = PersistenceController.shared     @State private var items = PersistenceController.shared.getItems()     @State private var showingEditView = false     @State private var showingAddView = false          var body: some View {         NavigationView{             List{                 Section(""){                     ForEach(items) { item in                         NavigationLink(destination: ItemView(item: item)){                             Text(item.name!)                         }                         .contextMenu{                             Button(action: {                                 self.showingEditView.toggle()                             }){                                 Text("Edit Item")                             }                             .sheet(isPresented: $showingEditView){                                 EditItemView(item: item)                                     .onDisappear(perform: {                                         items = persistence.getItems()                                     })                             }                         }                     }                     .onDelete(perform: { indexSet in                         deleteItem(indexSet: indexSet)                     })                 }             }             .listStyle(InsetGroupedListStyle())             .cornerRadius(10)             .navigationBarTitle("My Items")             .navigationBarItems(trailing: addButton)             .onAppear(perform: {                 items = persistence.getItems()             })             .sheet(isPresented: $showingAddView){                 AddItemView()                     .onDisappear(perform: {                         items = persistence.getItems()                     })             }         }     }          var addButton: some View {         Button(action: {             showingAddView.toggle()         }){             Text("Add an Item").bold()         }     }          func deleteItem(indexSet: IndexSet){         withAnimation{             indexSet.map {                 items[$0] }                         .forEach(managedObjContext.delete)                          persistence.contextSave()             items = persistence.getItems()         }     } } Item View: struct ItemView: View{     @State var item: Item     var body: some View{         Text(item.name ?? "No Name")     } } Add View: struct AddItemView: View{     @Environment(\.dismiss) var dismiss     @ObservedObject var persistence = PersistenceController.shared     @State private var name = ""     var body: some View {         Form{             TextField("Item Name", text: $name)             Button(action:{                 persistence.addItem(name: name)                 dismiss()             }){                 Text("Add Item")             }         }     } } Edit View: struct EditItemView: View{     @Environment(\.dismiss) var dismiss     @ObservedObject var persistence = PersistenceController.shared     @State var item: Item     @State private var name = ""     var body: some View {         Form{             TextField("Item Name", text: $name)             Button(action:{                 persistence.addItem(name: name)                 dismiss()             }){                 Text("Add Item")             }         }         .onAppear{             name=item.name ?? "No Name"         }     } } Persistence File: class PersistenceController : ObservableObject{     static let shared = PersistenceController()     let container: NSPersistentContainer          init(inMemory: Bool = false) {         container = NSPersistentContainer(name: "Test")         if inMemory {             container.persistentStoreDescriptions.first!.url = URL(fileURLWithPath: "/dev/null")         }         container.loadPersistentStores(completionHandler: { (storeDescription, error) in             if let error = error as NSError? {                 fatalError("Unresolved error \(error), \(error.userInfo)")             }         })         container.viewContext.automaticallyMergesChangesFromParent = true     }     static var preview: PersistenceController = {         let result = PersistenceController(inMemory: true)         let viewContext = result.container.viewContext         for _ in 0..<10 {             let newItem = Item(context: viewContext)             newItem.id = UUID()             newItem.name = "Test"         }         do {             try viewContext.save()         } catch {             let nsError = error as NSError             fatalError("Unresolved error \(nsError), \(nsError.userInfo)")         }         return result     }()     func getItems() -> [Item] {         let context = container.viewContext         var request = NSFetchRequest<Item>()         request = Item.fetchRequest()         request.entity = NSEntityDescription.entity(forEntityName: "Item", in: context)         do {             let items = try context.fetch(request)             if items.count == 0 { return []}             return items.sorted(by: {$0.name! > $1.name!})         } catch {             print("**** ERROR: items fetch failed \(error)")             return []         }     }          func addItem(name: String){         let context = container.viewContext         let item = Item(context: context)         item.id = UUID()         item.name = name                  contextSave()     }          func contextSave() {         let context = container.viewContext         if context.hasChanges {             do {                 try context.save()                 self.objectWillChange.send()             } catch {                 print("**** ERROR: Unable to save context \(error)")             }         }     } } Data Model:
Posted
by
Post not yet marked as solved
2 Replies
138 Views
Hi, I recently had an issue with one of my production apps that use Core Data and CloudKit where data wasn't syncing between devices, after a little bit of research I found out that the schema in the private CloudKit container needed to be initialized; which I never did. The part I'm still not 100% sure is when to run the initializeCloudKitSchema method after the app has been released to the AppStore. I see that Apple recommends running it when testing by using #if DEBUG, but... do you really want to run it every time you compile in Xcode? Here is how I understand it at this point... App release, call initializeCloudKitSchema() to match schemas between Core Data and CloudKit. Added or deleted an attribute, call initializeCloudKitSchema() to update the CloudKit schema. Renamed an attribute, call initializeCloudKitSchema() to update the CloudKit schema. Etc. If my assumption above is correct, calling the initializeCloudKitSchema() method during development would update the schema in CloudKit before the new app version is released in the AppStore, therefore creating an issue for existing users with previous versions of the app since they will not have the latest code but will be using the latest schema which contains the new attributes. Can someone please share their method of handling schema updates in CloudKit after the app has been released to the AppStore? Code: do { try container.initializeCloudKitSchema() } catch { print(error) }
Posted
by
Post not yet marked as solved
0 Replies
91 Views
Hi, I have an NSPredicate with format: "ANY containsEntity.id == %lld" I was trying to not-it, but the following don't work: NSCompoundPredicate(notPredicateWithSubpredicate: myPredicate) "NOT(ANY containsEntity.id == %lld)" "NONE containsEntity.id == %lld" containsEntity is a one to many relationship Is this a bug, as the following link may indicate? https://stackoverflow.com/questions/14471910/nspredicate-aggregate-operations-with-none Using the SUBQUERY workaround detailed in that link, adapted to my own query, provided the desired predicate functionality. SUBQUERY(containsEntity, $a, $a.id ==%lld).@count ==0" If it's a bug, that's a surprisingly long lived one, please fix it. Otherwise, I'd be grateful if someone could explain what I'm missing. Thank you in advance, Javier
Posted
by
Post not yet marked as solved
0 Replies
105 Views
Does anyone know the best way to store core data using a calendar? The only way I could think is adding a date attribute and every time the date is changed on the calendar changing the NSPredicate to that date and if there isn’t one creating a new instance with that date as it’s date value. I’m certain this is not the best method, but I couldn’t think of any other, but I know I’m very limited in my SwiftUI knowledge. So any guidance would be greatly appreciated. For more insight into what I’m looking for see my previous post asking for advice on what to change about my own method: https://developer.apple.com/forums/thread/708915
Posted
by
Post not yet marked as solved
1 Replies
125 Views
I have a SwiftUI app that uses CloudKit and Core data to sync data between devices. Everything works fine when testing on devices in Xcode but not in production in the App Store. Can someone explain the typical process when deploying an app that uses CoreData + CloudKit? Is there anything that needs to be done in code or in the CloudKit Console before the app is uploaded to the App Store? Again, my issue is that data doesn't sync when trying to sync data between multiple devices in production but works fine when testing in Xcode. Thanks
Posted
by
Post not yet marked as solved
2 Replies
256 Views
Basically I need a view with a calendar that will show data attributes from the item. I've tried two different approaches both have their listed problems. There must be a better way to do something like this. Surely it's not ideal to create a new item every time a date is opened or constantly check if something is there, but I don't know any other way. Actual View: import SwiftUI import CoreData struct ContentView: View {     @Environment(\.managedObjectContext) var managedObjContext     @Environment(\.calendar) var calenda     @Environment(\.dismiss) var dismiss     @FetchRequest(sortDescriptors: [], predicate: NSPredicate(format: "timestamp == %@", Date.now as CVarArg)) var items: FetchedResults<Item>          @State private var date = Date.now          var body: some View {         NavigationView{             VStack{                 DatePicker("Calendar", selection: $date, in: Date.now...,displayedComponents: [.date])                     .datePickerStyle(.graphical)                     .onAppear(perform: {                         if (items.isEmpty){                             PersistenceController().addItem(date: date, context: managedObjContext)                         }                     })                     .onChange(of: date){ value in                         items.nsPredicate=NSPredicate(format: "timestamp == %@", date as CVarArg)                         if (items.isEmpty){                             PersistenceController().addItem(date: date, context: managedObjContext)                         }                     }                 if (!items.isEmpty){ //This is the only difference in the two approaches. I just put either one of the next two blocks of code in here                 }             }             .navigationBarTitle("My Planner")         }     }          func getTitle(date: Date)->String{         let formatter = DateFormatter()         formatter.dateStyle = .medium         return formatter.string(from: date)     } } First (looks correct, but doesn't show the changes live): PlannedMealsView(item: items[0]) Spacer() //And then this is added at the bottom struct PlannedMealsView: View {     @Environment(\.managedObjectContext) var managedObjContext     @State var item: Item     var body: some View {             VStack{                 Text(item.timestamp ?? Date.now, style: .date)                     .font(.title2)                     .bold()                 Section("Word"){                     if(item.word != nil){                         HStack{                             Spacer()                             Text(item.word!)                             Spacer()                             Button(action: {                                 PersistenceController().removeFromItem(item: item, context: managedObjContext)                             }){                                 Image(systemName: "minus.circle").bold()                             }                             Spacer()                         }                     } else {                         Button(action: {                             PersistenceController().addToItem(item: item, context: managedObjContext)                         }){                             Image(systemName: "plus.circle").bold()                                 .padding(.vertical, 10)                                 .padding(.horizontal, 20)                         }                     }                 }                 Spacer()             }             .frame(height:200)     } } Second (allows direct access to the objects data, but bugs after 5 or 6 date changes): VStack{                             Text(items[0].timestamp ?? Date.now, style: .date)                                 .font(.title2)                                 .bold()                             Section("Word"){                                 if(items[0].word != nil){                                     HStack{                                         Spacer()                                         Text(items[0].word!)                                         Spacer()                                         Button(action: {                                             PersistenceController().removeFromItem(item: items[0], context: managedObjContext)                                         }){                                             Image(systemName: "minus.circle").bold()                                         }                                         Spacer()                                     }                                 } else {                                     Button(action: {                                         PersistenceController().addToItem(item: items[0], context: managedObjContext)                                     }){                                         Image(systemName: "plus.circle").bold()                                             .padding(.vertical, 10)                                             .padding(.horizontal, 20)                                     }                                 }                             }                         Spacer()                     }                     .frame(height:200) Unchanged Files: Persistence- import CoreData struct PersistenceController {     static let shared = PersistenceController()     let container: NSPersistentContainer     init(inMemory: Bool = false) {         container = NSPersistentContainer(name: "Test")         if inMemory {             container.persistentStoreDescriptions.first!.url = URL(fileURLWithPath: "/dev/null")         }         container.loadPersistentStores(completionHandler: { (storeDescription, error) in             if let error = error as NSError? {                 fatalError("Unresolved error \(error), \(error.userInfo)")             }         })         container.viewContext.automaticallyMergesChangesFromParent = true     }          func addItem(date: Date, context: NSManagedObjectContext){         let item = Item(context: context)         item.timestamp = date         item.word = nil                  save(context: context)     }          func addToItem(item: Item, context: NSManagedObjectContext){         item.word = "Test"                  save(context: context)     }          func removeFromItem(item: Item, context: NSManagedObjectContext){         item.word = nil                  save(context: context)     }          func save(context: NSManagedObjectContext){         do {             try context.save()         } catch {             let nsError = error as NSError             fatalError("Unresolved error \(nsError), \(nsError.userInfo)")         }     } } Data Model- If you have any questions I'll be happy to answer. Any help is greatly appreciated. All the best!
Posted
by
Post not yet marked as solved
0 Replies
93 Views
There was a section in the talk about how we can break down migration into smaller changes, and that we have an opportunity to run app-specific code in between migration steps. However the talk didn't touch on how can can achieve this, besides a single sentence, which doesn't give enough detail at least for me to figure out how to do it. Intuitively, an event loop could be built that opens the persistent store with the lightweight migration options set and iteratively steps through each unprocessed model in a serial order, and Core Data will migrate the store. Given the automatic nature of the lightweight migrations, especially in the case where we're using NSPersistentCoordinator, doesn't the automatic system just zoom through all of the migrations from model A --> A' --> A'' -> B? How to we make it stop so we can execute our own app code? Thanks!
Posted
by
Post not yet marked as solved
2 Replies
163 Views
Anyone know how to load a large number of records into the CloudKit public database? I need to load 1.2million records (about 150Mb) into the public database. no binary data. basically just a bunch of exchange rates that I need to have available to all my users. I've been trying for months. have tried: loading into core data on a device or simulator individually or in batches ranging from 400 records to 2500 (more than that exceeds batch size limits). it will start to sync and then stop. can often get it to restart by restarting device or similator but will eventually corrupt the database in iCloud requiring a reset of the environment. generally can get the load to go for a few days and load maybe 500k records before it breaks. to do that have to put delays up to a minute between batches loaded into core data. have tried doing it using the CloudKit.js framework and loading from a server. this works for a small number of records. but limits are really small doing it through that interface. after a while it locks you out. don't get anywhere near the number of records I need to load. I'm stuck. has anyone found a way? same issue on all versions of iOS - 14, 15, 16b1
Posted
by
ngb
Post not yet marked as solved
0 Replies
94 Views
Hi, any side effect to be aware of when changing a core data relationship delete rule from Null to Cascade? I NSPersistentCloudKitContainer to handle CloudKit sync in case that's relevant. It doesn't look like any migration is required, and the cloudkit schema doesn't change so it seems there's nothing to do on the cloudkit-side either. However I'd prefer to double check to avoid making false assumptions. I wasn't able to find any documentation on that particular point so if someone can shade some light on how things work under the hood that would be appreciated. Thanks!
Posted
by
0o0
Post not yet marked as solved
1 Replies
173 Views
I am trying to add CloudKit sharing to my app using the new iOS 15 share method  https://developer.apple.com/documentation/coredata/nspersistentcloudkitcontainer/3746834-sharemanagedobjects In the app there are 3 core data entities (Folder, Item, Comment) with the following relationships: A Folder contains many Items An Item has many Comments I want to use CloudKit to share just the Item entity, not any of its relationships. Is this possible to do with the share(_:to:completion:) method? Currently, when I pass an Item to the share method it also includes the Folder and Comments in the CKShare. How do I prevent this? A similar question was posted here with no response: https://developer.apple.com/forums/thread/697630
Posted
by
Post marked as solved
1 Replies
167 Views
I had the idea of adding a list feature in my app where users can create a list and add multiple recipes to the app so first and only thing I did was add an entity to my data model called "List" that contains a string: title and an array of Recipes: recipes (I remembered to put "NSSecureUnarchiveFromData" in Transformer and put [Recipe] for custom class). Afterwards I made the relationship in both entities and made them inverse. I made no other changes to my code. But I ran it just to make sure nothing went wrong and lo and behold: 7 never before seen errors, but only in one file. Before adding this entity this same code compiled just fine. This is the file and these are the errors I'm getting. Any help would be greatly appreciated. import SwiftUI struct RecipeView: View {     @Environment (\.managedObjectContext) var managedObjContext     @Environment(\.dismiss) var dismiss          var recipe: FetchedResults<Recipe>.Element     @State var isFavorite: Bool     @State var servings = -1          var body: some View {         VStack(alignment: .leading){ //Error: Trailing closure passed to parameter of type 'CGFloat?' that does not accept a closure             if (recipe.notes! != ""){                 Section{                     Text(recipe.notes!)                         .font(.headline)                 }                 .padding(.horizontal)             }             HStack{                 Spacer()                 Text("Total Time: "+calcTime(time:Int(recipe.totalTime!) ?? 0))                 Spacer()                 Text("Servings: "+recipe.servings!)                 Spacer()             }             .padding(.vertical)             Grid{                 GridRow{                     Button {                         isFavorite.toggle()                         recipe.isFavorite.toggle()                         PersistenceController().save(context: managedObjContext)                     } label: {                         HStack{                             Image(systemName: isFavorite ? "star.fill" : "star")                                 .foregroundStyle(.yellow)                             Text(isFavorite ? "Unfavorite" : "Favorite")                                 .foregroundColor(Color(UIColor.lightGray))                         }                         .frame(width: 300,height: 50)                         .background(Color(UIColor(hexString: "#202020")))                         .border(Color(UIColor(hexString: "#202020")))                         .cornerRadius(5)                     }                     Button {                         print("implement list functionality")                     } label: {                         Image(systemName: "plus")                             .frame(width: 50,height: 50)                             .background(Color(UIColor(hexString: "#202020")))                             .border(Color(UIColor(hexString: "#202020")))                             .cornerRadius(5)                     }                 }             }             .padding(.horizontal)             List{                 NavigationLink(destination: ingredientsView(ingredients: recipe.ingredients!)){                     HStack{                         Text("List of Ingredients")                         Spacer()                         Text(String(recipe.ingredients!.count))                             .foregroundColor(.gray)                     }                 }                 .frame(height: 50)                 NavigationLink(destination: instructionsView(instructions: recipe.instructions!)){                     HStack{                         Text("List of Instructions")                         Spacer()                         Text(String(recipe.instructions!.count))                             .foregroundColor(.gray)                     }                 }                 .frame(height: 50)             }             .listStyle(.grouped)             .scrollDisabled(true)             Spacer()         }         .navigationBarTitle(recipe.title!)         .navigationBarItems(trailing: shareButton)         .onAppear{             PersistenceController().updateDate(recipe: recipe, context: managedObjContext)         }         Spacer()     }     var shareButton: some View{         Button(action: {             print("Implement airdrop feature")         }){             Image(systemName: "square.and.arrow.up")                 .foregroundStyle(.blue)         }     } } struct ingredientsView: View{     @State var ingredients: [String]     var body: some View{         List{ // Error: Trailing closure passed to parameter of type 'NSManagedObjectContext' that does not accept a closure             Section(""){                 ForEach(ingredients,id: \.self){ String in                     NavigationLink(destination:                                     NavigationView{                         Text(String)                             .frame(alignment:.center)                             .font(.title)                     }){                         Text(String).lineLimit(1)                     }                 }             }         }         .frame(alignment: .center) //Error: Cannot infer contextual base in reference to member 'center' //Error: Value of type 'List' has no member 'frame'         .cornerRadius(10)         .navigationTitle("Ingredients List")     } } struct instructionsView: View{     @State var instructions: [String]     var body: some View{         List{ // Error: Trailing closure passed to parameter of type 'NSManagedObjectContext' that does not accept a closure             Section(""){                 ForEach(instructions,id: \.self){ String in                     NavigationLink(destination:                                     NavigationView{                         Text(String)                             .frame(alignment:.center)                             .font(.title)                     }){                         Text(String).lineLimit(1)                     }                 }             }         }         .frame(alignment: .center) //Error: Cannot infer contextual base in reference to member 'center' //Error: Value of type 'List' has no member 'frame'         .cornerRadius(10)         .navigationTitle("Instructions List")     } }
Posted
by
Post marked as solved
4 Replies
235 Views
So I was making a relationship between two entities in my data model and got a good ways in when I tried to run it and got a bunch of weird errors. Did I do something wrong to make this happen and if so what do I need to do? I've troubleshooted enough to realize that it happens as soon as I create a new entity. These are the errors.
Posted
by
Post not yet marked as solved
6 Replies
262 Views
Hi. I want to make a planner app that has the date and location of the project. Only I have a problem. I used a "DatePicker" so that the date is counted. Only I do not know how to save and display the selected date. In general I have problems to save and reload the content of the variables and texfielders etc. I thought that these contents are automatically saved on the end device of the user. I have read that there are methods like "UserDefaults", "CoreData" or "AppStorage". Have been reading stuff about this forever. But I can't get this to work. I hope someone would like to donate their time to help. Greetings Janik
Posted
by
Post not yet marked as solved
2 Replies
138 Views
I have a class with a parameter in the form class class_name: Codable { var array_name = [] } Running the code, I see I can add numbers in the array. But when I get the array in another function it says it is empty. I do it with: let new_class = class_name() Can it happen that the value gets reseted for calling the class again?
Posted
by
Post marked as solved
1 Replies
179 Views
I'm working on hooking up a Multiplatform app with CloudKit (using CoreData) and I was wondering if anyone knows any current tutorials to help me understand the process better? I was trying to wrap my head around the WWDC 2022 tutorial CoreDataCloudKitDemo but it isn't SwiftUI and I'm getting bogged down by the non-relevant code. Thanks everyone :)
Posted
by
Post marked as solved
2 Replies
243 Views
So I've found a way to convert fetched results to an array of the same data type, and not only that but filter them with the fetch request given a string: func searchResults(searchingFor: String)->[Recipe]{     var filteredRecipeList=[Recipe]()     @FetchRequest(sortDescriptors: [SortDescriptor(\.date, order: .reverse)], predicate: NSPredicate(format: "title CONTAINS[c] %@",searchingFor)) var filteredResults: FetchedResults<Recipe>     for recipe in filteredResults {         filteredRecipeList.append(recipe)     }     return filteredRecipeList } To clarify, this would ideally return an array with a list of Recipes that contain the given string in the title. In theory this should work just fine, but I'm getting a weird error. I've never seen an error like this and I'm not sure how to understand it. It is purple with a yellow warning. The error says "Accessing StateObject's object without being installed on a View. This will create a new instance each time." How do I get around this issue to accomplish what I'm trying to accomplish. Thanks in advance for any help whatsoever. I'll upvote anyone with any bit of helpful information. Have a good one!
Posted
by
Post not yet marked as solved
1 Replies
227 Views
So I have a core data entity titled recipe. I'm trying to make a search bar to search the list of recipes and my method of doing so is doing a fetch request of all objects and converting it to an array of those objects and then filtering the array and displaying the results. Any idea as to how to convert a type fetch results to an array? PS: as I'm typing this it occurred to me I could just do a for each loop and add them to the array as I go, but is there a quicker way to do this? Like a function? Thanks!!!
Posted
by
Post not yet marked as solved
2 Replies
188 Views
So I have an entity in my core data model called recipe. I need to create another entity containing a recipe and a date that the recipe is assigned to. Can I do this similar to the way I've done it in the image and just save a Recipe object in the initialization of PlannedRecipe object in the Persistence file? Basically I just need to know how to add a entity in an entity using this core data model and persistence file. Persistence file: import CoreData struct PersistenceController {     static let shared = PersistenceController()     let container: NSPersistentCloudKitContainer     init(inMemory: Bool = false) {         container = NSPersistentCloudKitContainer(name: "ReciPrep")         if inMemory {             container.persistentStoreDescriptions.first!.url = URL(fileURLWithPath: "/dev/null")         }         container.loadPersistentStores(completionHandler: { (storeDescription, error) in             if let error = error as NSError? {                 fatalError("Unresolved error \(error), \(error.userInfo)")             }         })         container.viewContext.automaticallyMergesChangesFromParent = true     }     func addPlannedRecipe(recipe: Recipe,date: Date, context: NSManagedObjectContext){         let plannedRecipe = PlannedRecipe(context: context)         plannedRecipe.id = UUID()         plannedRecipe.date = Date()         plannedRecipe.recipe = recipe //Giving me an error: "Cannot assign value of type 'Recipe' to type 'Data?'"                  save(context: context)     }          func save(context: NSManagedObjectContext){         do {             try context.save()         } catch {             let nsError = error as NSError             fatalError("Unresolved error \(nsError), \(nsError.userInfo)")         }     } } I guess this problem can be solved if I can convert a recipe into binary data or some other savable data in an entity. Any help would be greatly appreciated.
Posted
by