M6L4 : Enhanced Featured View

Continuing with enhancing our (old) Recipe App with Core Data, lesson 4 from module 6 of the CWC+ iOS Satabases Course takes us through some important changes.

We previously got all of our data from our RecipeModel, re:

@EnvironmentObject var model:RecipeModel

And we displayed the data, thus –

Text(model.recipes[index].name)

Now we’re using Core Data, we use:

@FetchRequest(
    sortDescriptors: [NSSortDescriptor(key: "name", ascending: true)],
    predicate: NSPredicate(format: "featured == true")
)
var recipes: FetchedResults<Recipe>

FetchedResults is returned as an array similar to RecipeModel that we used before, meaning that we can change all code that referenced model.recipes into simply recipes, thus –

Text(recipes[index].name)

In the tutorial video, the “Featured” recipes were shown in reverse alphabetical order but, strangely, mine was in the correct order. Nevertheless, Chris takes us through the method of sorting our results, thus –

@FetchRequest(
    sortDescriptors: [NSSortDescriptor(key: "name", ascending: true)],
    predicate: NSPredicate(format: "featured == true")
)

Also, we previously looped though all recipes (from model:RecipeModel) using an if ... statement to display only those recipes marked as “featured”, as follows –

if model.recipes[index].featured == true {
    ...
}

However, a more code-efficient way of doing this is by using predicate as we previously discussed in Lesson 4 of Module 5. By calling up the following, we don’t need the if ... statement.

@FetchRequest(
    sortDescriptors: [NSSortDescriptor(key: "name", ascending: true)],
    predicate: NSPredicate(format: "featured == true")
)

This all makes far more sense to me because I would previously sort and filter data requests in SQL query statements when I worked on PHP & MySQL / MariaDB in past years, and so doing the sorting/filtering prior to using the data seems more natural.