简体   繁体   中英

Searching number of relationships in Core Data - Swift

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>
    }
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM