Mastering iOS 10 Programming by Donny Wals

Mastering iOS 10 Programming by Donny Wals

Author:Donny Wals [Wals, Donny]
Language: eng
Format: azw3, mobi
Publisher: Packt Publishing
Published: 2016-12-21T05:00:00+00:00


Great, the model has been updated. We still need to perform a bit of work though. Because we changed the name and nature of the family member relationship, our code won't compile. Make the following modifications to the managedObjectContextDidChange(_:) method in MoviesViewController.swift; the modified lines are highlighted:

if let updatedObjects = userInfo[NSUpdatedObjectsKey] as? Set<Movie> { for object in updatedObjects { if let familyMember = self.familyMember, let familyMembers = object.familyMembers where, familyMembers.contains(familyMember) { tableView.reloadData() break } } }

There is just one more model-related change that we will need to incorporate. In order to efficiently search for an existing movie or create a new one, we will add an extension to the Movie model. Create a new group called Models and add a new Swift file named Movie.swift to it. Finally, add the following implementation to the file:

import CoreData extension Movie { static func find(byName name: String, orCreateIn moc: NSManagedObjectContext) -> Movie { let predicate = Predicate(format: "name ==[dc] %@", name) let request: NSFetchRequest<Movie> = Movie.fetchRequest() request.predicate = predicate guard let result = try? moc.fetch(request) else { return Movie(context: moc) } return result.first ?? Movie(context: moc) } }

The preceding code will query CoreData for an existing movie with the same name. This matching will be done case insensitively because people might write the same movie name with different capitalization. If we aren't able to find a result, or if the results come back empty, we will create a new movie. Otherwise, we return the first and presumably the only result CoreData has for our query. This wraps up the changes we need to make to our data layer.



Download



Copyright Disclaimer:
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.