所以我有两个实体。列表和评论。列表可以包含多个相关注释。
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]
}
这样可以正常工作,但是如何使用具有特定评级的评论来过滤掉所有列表?
答案 0 :(得分:1)
由于comments
是to-Many关系,因此您需要帮助CoreData解决您关注的问题:ALL,ANY或NONE。例如:
fetchRequest.predicate = NSPredicate(format: "ANY comments.rating > 4")
仅包含Listings
Comments
的任何fetchRequest.predicate = NSPredicate(format: "ALL comments.rating < 2")
评分为4或更高,而:
Comments
仅当所有.split()
的评分均小于2时,才会包含它们。