Post

Replies

Boosts

Views

Activity

Unknown Errors From Inverse Relationship. Please Help!!!
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")     } }
2
1
1.5k
Jun ’22
Enlarged TextField
I need to enlarge my text field. So I tried using a frame, but that only put dead space around it. The problem with that is I want to be able to click anywhere inside the boarder and it pull up the keyboard. So I tried padding and that did the same thing. Also I need the text to start a new line after it fills the first one and to go for as long as they type. Thanks!
1
0
405
Jun ’22
NavBar Format
How has GitHub formatted their navigation bar like this? The title is aligned with the back button and add button, the search bar is inside instead of under, and they have buttons alone the bottom that filter the list. Is there a view object that shortcuts this? If you understand even one part of that I would appreciate that information. Thanks!
0
0
342
Jun ’22
List Background
Does anyone have any clue as to how to get rid of the grey background of my list? I've actually tried everything I could find online. .background(Color.clear), .backgroundStyle(.clear), init(){...}. nothing. I even tried replicating it in a new project and it didn't even show up there. Any idea as to how to get rid of this?
1
0
483
Jun ’22
Airdrop CoreData
I need to share a singular instance of an object created in core data. Every video I've found that showed how to do this used outdated code and I was wondering if anyone had a working way to either create the airdrop button (because I don't even know how to do that yet, or make it so that the data is share is a duplicate of the object from the sharers device. Thanks! This is the entity that needs to be shared via airdrop:
0
0
309
Jun ’22
Filtering an Array
I'm trying to filter an array containing Recipes that have a property called title of type String that is required. These are the variables used in the line of code: @State private var searchingFor = "" @State private var filteredRecipes = [Recipe]() This is the line of code giving me the error: filteredRecipes=filteredRecipes.filter{$0.title.contains(searchingFor)} The error: "Value of optional type 'String?' must be unwrapped to refer to member 'contains' of wrapped base type 'String'" Any ideas on how I need to rewrite that line of code so that I don't get that error? ie. how do I unwrap 'String?'
3
0
1.2k
Jun ’22
Core Data Entity Inside Another Entity
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.
2
0
1.1k
Jun ’22
FetchedResults to Array
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!!!
1
0
2.6k
Jun ’22
Dynamically Filtering a FetchRequest
I am trying to implement a search bar in my recipe storage app. I got recommended using the .filter function that I didn’t know could be used on FetchedResults. So I did and now I’m getting errors, but not ones saying that it isn’t in the scope so I believe this is possible, just now sure how. The ForEach loop containing the filter: •ForEach(recipes.filter({$0.title.contains(searchingFor)})) { recipe in Note: Recipes is just a FetchedResults type and searchingFor is just a string that comes from the search bar. The errors: •Value of optional type 'String?' must be unwrapped to refer to member 'contains' of wrapped base type 'String' •Chain the optional using '?' to access member 'contains' only for non-'nil' base values •Force-unwrap using '!' to abort execution if the optional value contains 'nil' Any help is greatly appreciated.
1
0
1.2k
Jun ’22
Default Keyboard Toolbar
Whenever I open a text field almost anywhere I get this common toolbar above my keyboard with two arrows that iterate through text fields and a done button. Not just on Apple related things, but even when I search on google. Which leads me to believe this is a default object and that google did not take the time to make an identical keyboard toolbar as all of Apple’s. So how do I get this default toolbar? toolbar:
1
0
917
Jun ’22
Searching with @FetchRequest
So I've made a function using FetchRequest to search, but im getting an error: "Accessing StateObject's object without being installed on a View. This will create a new instance each time." The function takes a string and searches the core data for objects containing that string. The string is obtained from a .searchable object and the function is ran as a ForEach parameter. This is the function: func searchResults(searchingFor: String) -> FetchedResults<Recipe> {         @FetchRequest(sortDescriptors: [SortDescriptor(\.date, order: .reverse)], predicate: NSPredicate(format: "title CONTAINS[c] %@",searchingFor)) var searchRecipes: FetchedResults<Recipe>         return searchRecipes     } Is there a better way to do this or can I do it this way and tweak it a little bit? I really just need to have a search bar that returns a FetechedResults type so I can use it in a ForEach loop. Any help is greatly appreciated.
3
0
709
Jun ’22
Data Persistence using Core Data
So I created a program without selecting “use core data” and realized after trying to make a persistence data storage that it helps very much so I created a new program and selected it this time and copied everything over. It provided a file called “Persistence” and the contentView file had a bunch of stuff already filled in (Also something called the title of the program). I have the data I need saved to the persistent data storage narrowed down to a singular array, but none of the videos I found online showed this version of xcode that supplied a “Persistence” file when using core data so I’m unsure how to use it. I will provide the contentView and Persistence file for context. The array I need saved is called mainList in contentView. ContentView: import SwiftUI import CoreData struct ContentView: View {     var mainList = [RecipeList(),RecipeList(),RecipeList(),RecipeList(),RecipeList()]          @Environment(\.managedObjectContext) private var viewContext     @FetchRequest(         sortDescriptors: [NSSortDescriptor(keyPath: \Item.timestamp, ascending: true)],         animation: .default)     private var items: FetchedResults<Item>     var body: some View {         NavigationView {             List {                 ForEach(items) { item in                     NavigationLink {                         Text("Item at \(item.timestamp!, formatter: itemFormatter)")                     } label: {                         Text(item.timestamp!, formatter: itemFormatter)                     }                 }                 .onDelete(perform: deleteItems)             }             .toolbar {                 ToolbarItem(placement: .navigationBarTrailing) {                     EditButton()                 }                 ToolbarItem {                     Button(action: addItem) {                         Label("Add Item", systemImage: "plus")                     }                 }             }             Text("Select an item")         }     }     private func addItem() {         withAnimation {             let newItem = Item(context: viewContext)             newItem.timestamp = Date()             do {                 try viewContext.save()             } catch {                 // Replace this implementation with code to handle the error appropriately.                 // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.                 let nsError = error as NSError                 fatalError("Unresolved error \(nsError), \(nsError.userInfo)")             }         }     }     private func deleteItems(offsets: IndexSet) {         withAnimation {             offsets.map { items[$0] }.forEach(viewContext.delete)             do {                 try viewContext.save()             } catch {                 // Replace this implementation with code to handle the error appropriately.                 // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.                 let nsError = error as NSError                 fatalError("Unresolved error \(nsError), \(nsError.userInfo)")             }         }     } } private let itemFormatter: DateFormatter = {     let formatter = DateFormatter()     formatter.dateStyle = .short     formatter.timeStyle = .medium     return formatter }() struct ContentView_Previews: PreviewProvider {     static var previews: some View {         ContentView().environment(\.managedObjectContext, PersistenceController.preview.container.viewContext)     } } Persistence: import CoreData struct PersistenceController {     static let shared = PersistenceController()     static var preview: PersistenceController = {         let result = PersistenceController(inMemory: true)         let viewContext = result.container.viewContext         for _ in 0..<10 {             let newItem = Item(context: viewContext)             newItem.timestamp = Date()         }         do {             try viewContext.save()         } catch {             // Replace this implementation with code to handle the error appropriately.             // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.             let nsError = error as NSError             fatalError("Unresolved error \(nsError), \(nsError.userInfo)")         }         return result     }()     let container: NSPersistentCloudKitContainer     init(inMemory: Bool = false) {         container = NSPersistentCloudKitContainer(name: "ReciStorage")         if inMemory {             container.persistentStoreDescriptions.first!.url = URL(fileURLWithPath: "/dev/null")         }         container.loadPersistentStores(completionHandler: { (storeDescription, error) in             if let error = error as NSError? {                 // Replace this implementation with code to handle the error appropriately.                 // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.                 /*                  Typical reasons for an error here include:                  * The parent directory does not exist, cannot be created, or disallows writing.                  * The persistent store is not accessible, due to permissions or data protection when the device is locked.                  * The device is out of space.                  * The store could not be migrated to the current model version.                  Check the error message to determine what the actual problem was.                  */                 fatalError("Unresolved error \(error), \(error.userInfo)")             }         })         container.viewContext.automaticallyMergesChangesFromParent = true     } } Image showing the thing named the title of the program that I’m certain is relevant to the persisting data storage: Also I’m unsure what I need to replace those comments with and what subclasses I should add to existing swift files like “codable” for example. Any help would be greatly appreciated.
2
1
1.8k
Jun ’22