为了实现(我认为)你想要的,我不得不求助于两个单独的提取。country
对于 和 的每个不同组合,第一次获取获取一个对象的 objectID city
。使用IN
谓词将第二次提取过滤到这些对象。它使用NSExpression
andpropertiesToGroupBy
来获取每个的计数country
:
// Step 1, get the object IDs for one object for each distinct country and city
var objIDExp = NSExpression(expressionType: NSExpressionType.EvaluatedObjectExpressionType)
var objIDED = NSExpressionDescription()
objIDED.expression = objIDExp
objIDED.expressionResultType = .ObjectIDAttributeType
objIDED.name = "objID"
var fetch = NSFetchRequest(entityName: "Location")
fetch.propertiesToFetch = [objIDED]
fetch.propertiesToGroupBy = ["country", "city"]
fetch.resultType = .DictionaryResultType
let results = self.managedObjectContext!.executeFetchRequest(fetch, error: nil)
// extract the objectIDs into an array...
let objIDArray = (results! as NSArray).valueForKey("objID") as! [NSManagedObjectID];
// Step 2, count using GROUP BY
var countExp = NSExpression(format: "count:(SELF)")
var countED = NSExpressionDescription()
countED.expression = countExp
countED.expressionResultType = .ObjectIDAttributeType
countED.name = "count"
var newFetch = NSFetchRequest(entityName: "Location")
newFetch.predicate = NSPredicate(format: "SELF IN %@", objIDArray)
newFetch.propertiesToFetch = ["country", countED]
newFetch.propertiesToGroupBy = ["country"]
newFetch.resultType = .DictionaryResultType
let newResults = self.managedObjectContext!.executeFetchRequest(newFetch, error: nil)
println("\(newResults!)")
这将是低效的:如果您有大量不同的国家和城市,IN 谓词会减慢速度。您可能会发现获取所有内容并计算它们的效率更高。