Chapter23.Core Data Relationships-Silver Challenge [full] simple solution

Solution screenshots:

------------------------------------Implementation-----------------------------:
Core Data: Photo.isFavorite:

  • First thing first, I added isFavorite Boolean attribute for Photo entity in Photorama Core Data :

  • Second, I deleted Photo+CoreDataClass.swift & Photo+CoreDataProperties.swift files and regenerated files by selecting Photo entity and going to EditorCreate NSManagedObject Subclass… Now that we have our Core Data taking care of we can move on to implementing code and the Interface.

Every photo must be not favorite by default:

Now we can implement logic for favoriting and unfavoriting a Photo:

  • Adding RightBarButtonItem as a favorite/unfavorite button. I added a private func displayFavorite() in PhotoInfoViewController to do this (you might get an error typing, we will fix the error next):

  • Which adds the RightBarButtonItem with star filled background image if the photo is a favorite photo and regular (unfilled) star background image otherwise.

  • Fixing the error. We have an error because action function for button is missing, adding favoritePhoto():


    Upon clicking the button this function gets fired. And it favorites/unfavorites the photo (photo.isFavorite = !photo.isFavorite). Then saving the changes in Core Data in the next line (if we don’t save, changes won’t persist when closing the app and relaunching it). And finally updating background picture in the last line.

  • After calling our newly added funcion from viewDidLoad() in PhotoInfoViewController.swift this is the result (not favorite and favorite photos):


Now we can add a UISegmentedControl to switch the display between Regular photos and Favorite photos:

Update data source:

Navigating between ViewControllers will result in inconsistent data display:

  • When having multiple favorite photos, and viewing them in Favorite-Photos state using Segment Control, and tapping on a photo, it would take you to PhotoInfoViewController where you can still unfavorite them. But when clicking back and navigating back to PhotosViewController which in Favorite-Photos state would still display the photo we just unfavorite:

  • To fix this we want to update the UI whenever we navigate between PhotoInfoViewController.swiftPhotosViewController.swift. We do that by adding viewWillAppear(_ animated: Bool) func in PhotosViewController.swift. Call it’s super view and updateDataSource again:


    Now that problem is fixed. Also this would still work in a scenario where you are in Favorite-Photos state and have your last favorite photo, you tap on it to go to PhotoInfoViewController, unfavorite the photo and navigate back. Not only photo has been removed from favorite photos and not being displayed, but also you get a prompt saying “No Favorite Photos”:

Happy coding. Feel free to ask questions, suggest improvements or remind me if i missed any scenarios.