所以我有两个实体。清单和评论。一个列表可以有多个关联的注释。

extension Listing {

    @NSManaged var listingTitle: String?
    @NSManaged var comments: NSSet?
    @NSManaged var listingLatitude: Double
    @NSManaged var listingLongitude: Double
}

extension Comment {

    @NSManaged var comment: String?
    @NSManaged var commentId: String?
    @NSManaged var rating: Int32
    @NSManaged var username: String?
    @NSManaged var listing: Listing?

}


使用NSPredicate,我可以很容易地过滤掉位于特定地理区域内的列表。

// Fetching data from CoreData
            let fetchRequest = NSFetchRequest()
            fetchRequest.predicate = NSPredicate(format: "listingLatitude BETWEEN {%f,%f} AND listingLongitude BETWEEN {%f,%f}", (latitude-0.10), (latitude+0.10), (longitude-0.10), (longitude+0.10))
            let entity = NSEntityDescription.entityForName("Listing", inManagedObjectContext: self.mainMoc)
            fetchRequest.entity = entity

            fetchRequest.sortDescriptors = [sortDescriptor]

            do {
                listings = try self.mainMoc.executeFetchRequest(fetchRequest) as! [Listing]

            }


这可以正常工作,但是我如何完成过滤掉所有带有给定特定等级的注释的清单?

最佳答案

由于comments是一对多关系,因此您需要帮助CoreData找出您所关注的对象:ALL,ANY或NONE。因此,例如:

fetchRequest.predicate = NSPredicate(format: "ANY comments.rating > 4")


将仅包含其Listings的任何一项被评为4或更高的那些Comments,而:

fetchRequest.predicate = NSPredicate(format: "ALL comments.rating < 2")


仅当所有Comments的额定值小于2时,才会包括它们。

10-05 21:17