I'm trying to setup a filter option for some core data records, but I'm not seeing the expected results.
Essentially, what I want is to have multiple sections. Within each section it would be an OR query, and an AND between each section. I've tried setting it up as below.
func getBasicFilter() -> NSPredicate? {
var predicatesBagsLeft : [NSPredicate] = []
var predicatesDrillType : [NSPredicate] = []
var andPredicates : [NSPredicate] = []
print("Filter List")
print(filters)
// Bags Left
if let show = filters["showFullLeft"] {
if show {
print("Predicates : Show Full")
let predicate = NSPredicate(format: "ANY projectColours.fullLeft > 0")
predicatesBagsLeft.append(predicate)
}
}
if let show = filters["showPartialLeft"] {
if show {
print("Predicates : Show Partial")
let predicate = NSPredicate(format: "ANY projectColours.partialLeft > 0")
predicatesBagsLeft.append(predicate)
}
}
// Drill Types
if let show = filters["showSquareOnly"] {
if show {
print("Predicates : Show Square Only")
let predicate = NSPredicate(format: "ANY projectColours.project.drillType = %@", "Square")
predicatesDrillType.append(predicate)
}
}
// Drill Manufacturers - TO DO
// Combine Predicates
if predicatesBagsLeft.count > 0 {
let predicatesForBagsLeft = NSCompoundPredicate(type: .or, subpredicates: predicatesBagsLeft)
andPredicates.append(predicatesForBagsLeft)
}
if predicatesDrillType.count > 0 {
let predicatesForDrillType = NSCompoundPredicate(type: .or, subpredicates: predicatesDrillType)
andPredicates.append(predicatesForDrillType)
}
if andPredicates.count > 0 {
let predicates = NSCompoundPredicate(type: .and, subpredicates: andPredicates)
return predicates
}
return nil
}
It does filter, but doesn't seem to be applying both correctly. I'm testing with a filter of showFullLeft & showSquareOnly, so it should show only squares which have a a fullest > 0
I'm getting 7 results back, but one of them is unwanted. It is square, but it has 0 for both full & partial
When I look at the query core data is using it looks correct
CoreData: sql: SELECT t0.ZMANU, COUNT (DISTINCT t0.Z_PK) FROM ZCOLOUR t0 JOIN ZPROJECTCOLOUR t1 ON t0.Z_PK = t1.ZCOLOUR JOIN ZPROJECTCOLOUR t2 ON t0.Z_PK = t2.ZCOLOUR JOIN ZPROJECT t3 ON t2.ZPROJECT = t3.Z_PK WHERE ( t1.ZFULLLEFT > ? AND t3.ZDRILLTYPE = ?) GROUP BY t0.ZMANU ORDER BY t0.ZMANU
CoreData: details: SQLite bind[0] = 0
CoreData: details: SQLite bind[1] = "Square"