I set up a UISegmented Control to toggle between All Photos and Favorites in my PhotosViewController.swift and set up a new Predicate function to fetch my Favorites.
But when I run the app, nothing happens when I toggle (I only marked a handful of photos as Favorites).
PhotosViewController.swift:
// for Silver Challenge:
@objc func photoTypeChanged(_ segControl: UISegmentedControl) {
switch segControl.selectedSegmentIndex {
case 0:
store.fetchInterestingPhotos {
(photosResult) -> Void in
self.updateDataSource()
}
default:
store.fetchAllFavorites {
(photosResult) -> Void in
self.updateDataSource()
}
}
}
PhotoStore.swift:
// Silver Challenge
func fetchAllFavorites(completion: @escaping (Result<[Photo], Error>) -> Void) {
let fetchRequest: NSFetchRequest<Photo> = Photo.fetchRequest()
let sortByDateTaken = NSSortDescriptor(key: #keyPath(Photo.dateTaken), ascending: true)
fetchRequest.predicate = NSPredicate(format: "isFavorite == true")
fetchRequest.sortDescriptors = [sortByDateTaken]
let viewContext = persistentContainer.viewContext
viewContext.perform {
do {
let allPhotos = try viewContext.fetch(fetchRequest)
completion(.success(allPhotos))
} catch {
completion(.failure(error))
}
}
}
Is there something wrong with my predicate function? I tried to adapt what I found from this Apple resource:
[https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/CoreData/FetchingObjects.html#//apple_ref/doc/uid/TP40001075-CH6-SW1](https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/CoreData/FetchingObjects.html#//apple_ref/doc/uid/TP40001075-CH6-SW1)