Reputation: 388
My Core Data Model has two entities: Locations and Photos.
Location stores lat, lon and can have many photos associated to it. Photos store a picture as binary data. Inverse relationships are set as well.
For a given location how can I see if that entity currently has any photos associated with it?
I'm using an NSManagedObject class for locations and thought about searching through all photos, but that seemed rather inefficient.
class Location: NSManagedObject, MKAnnotation {
init (latitude: Double, longitude: Double, context: NSManagedObjectContext) {
if let ent = NSEntityDescription.entityForName("Location", inManagedObjectContext: context) {
super.init(entity: ent, insertIntoManagedObjectContext: context)
self.latitude = NSNumber(double: latitude)
self.longitude = NSNumber(double: longitude)
}
else {
fatalError("ERROR")
}
}
override init(entity: NSEntityDescription, insertIntoManagedObjectContext context: NSManagedObjectContext?) {
super.init(entity: entity, insertIntoManagedObjectContext: context)
}
func photoCount(context: NSManagedObjectContext) ->Int {
let fetchRequest = NSFetchRequest(entityName: "Photo")
let predicate = NSPredicate(format: "location = %@", self)
fetchRequest.predicate = predicate
??? Best Option ???
return <COUNT OF PHOTOS FOR LOCATION>
}
}
Upvotes: 0
Views: 235
Reputation: 70946
You're making this much more difficult than necessary. Since you say that there's a relationship from Location
to Photo
, all you need to do is look up the value of that relationship. When you already have a Location
, you can use its relationships directly without doing another fetch.
If you have
let location : Location = // assume this exists
And if Location
has a to-many relationship called photos
to entity Photo
, you get the count of photos as
let count = location.photos?.count
Upvotes: 1