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.

hi,

@FetchRequest in a SwiftUI construct to be included within a View that gives you access to an array of (what are essentially) Recipe objects for use within the View. it's not something where you procedurally say "give me a fetch of objects."

if your function is defined within a View, then the View should have a local variable that keeps up to date with all the recipes:

@FetchRequest(entity: Recipe.entity(), sortDescriptors: [
		NSSortDescriptor(keyPath: \Recipe.date, ascending: false)
	]) 
var recipes: FetchedResults<Recipe>

you can search through these recipes directly with

func searchResults(searchingFor: String) -> [Recipe] { 
    recipes.filter({ $0.title.contains(searchingFor) })
}

otherwise, you should execute a direct Core Data fetch, setting up an NSFetchRequest with appropriate NSSortDescriptors and NSPredicates to query Core Data.

hope that helps,

DMG

@FetchRequest is a SwiftUI construct ...

I’m getting some errors from:

func searchResults(searchingFor: String) -> [Recipe]{         var searchRecipes=recipe.filter({$0.title.contains(searchingFor)})         return searchRecipes     }

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'

Searching with @FetchRequest
 
 
Q