Reputation: 776
I am building a maps app with the following entities:
Coordinate to Map is to-one and Map to Coordinate is a to-many relationship.
And my code would be:
fileprivate var fetchedResultsControllerForMapEntity: NSFetchedResultsController<Map> = {
// Create Fetch Request
let fetchRequest: NSFetchRequest<Map> = Map.fetchRequest()
// Configure Fetch Request
fetchRequest.sortDescriptors = [NSSortDescriptor(key: "name", ascending: true)]
fetchRequest.predicate = NSPredicate(format:"newRelationship == %@", "peachesfarm")
// Create Fetched Results Controller
let fetchedResultsControllerForMapEntity = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: managedObjectContext, sectionNameKeyPath: nil, cacheName: nil)
return fetchedResultsControllerForMapEntity
}()
fileprivate var fetchedResultsControllerForCoordinateEntity: NSFetchedResultsController<Coordinate> = {
// Create Fetch Request
let fetchRequest: NSFetchRequest<Coordinate> = Coordinate.fetchRequest()
// Configure Fetch Request
fetchRequest.sortDescriptors = [NSSortDescriptor(key: "latitude", ascending: true)]
fetchRequest.sortDescriptors = [NSSortDescriptor(key: "longitude", ascending: true)]
// Create Fetched Results Controller
let fetchedResultsControllerForCoordinateEntity = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: managedObjectContext, sectionNameKeyPath: nil, cacheName: nil)
return fetchedResultsControllerForCoordinateEntity
}()
I am basically trying to retrieve the coordinates of the map called "peachesfarm" ONLY. Why might I be getting this exception?
Upvotes: 0
Views: 2015
Reputation: 539805
NSPredicate(format:"newRelationship == %@", "peachesfarm")
gives an error because "newRelationship" is a to-many relationship, which cannot be compared for equality.
To fetch all coordinates which are related to a map with a given name, you have to use a fetch request for "Coordinate", not for "Map". Then use the key path to the name of the related map. Using the relationship names as suggested by @vadian above that would be
let fetchRequest: NSFetchRequest<Coordinate> = Coordinate.fetchRequest()
let predicate = NSPredicate(format: "map.name == %@", "peachesFarm")
fetchRequest.predicate = predicate
Even better, use the #keyPath
directive, where the compiler checks
the property names so that errors are avoided:
let predicate = NSPredicate(format: "\(#keyPath(Coordinate.map.name)) == %@", "peachesFarm")
Upvotes: 2