是什么人。
我目前正在这样做:
var results = NSArray()
let appDel = UIApplication.sharedApplication().delegate as! AppDelegate
let context = appDel.managedObjectContext
let fetch = NSFetchRequest(entityName: "Work")
let entity = NSEntityDescription.entityForName("Work", inManagedObjectContext: context)!
let monthDesc = entity.attributesByName["shortMonth"] as NSAttributeDescription!
let keyPathExpression = NSExpression(forKeyPath: "date")
// Does not really matter
let countExpression = NSExpression(forFunction: "count:", arguments: [keyPathExpression])
let expressionDescription = NSExpressionDescription()
expressionDescription.name = "count"
expressionDescription.expression = countExpression
expressionDescription.expressionResultType = .Integer32AttributeType
fetch.propertiesToFetch = [monthDesc, expressionDescription]
fetch.propertiesToGroupBy = [monthDesc]
fetch.resultType = .DictionaryResultType
//var error: NSError? = nil
fetch.returnsObjectsAsFaults = false;
do {
results = try context.executeFetchRequest(fetch)
} catch {
print("Unable to fetch results")
abort()
}
let months = results.flatMap{$0["shortMonth"] as? String}
let countt = results.flatMap{$0["count"] as? Double}
print("Months \(months)")
print("Countt \(countt)")
这将带回两个数组,其中包含月份名称和该月份名称的记录数。
结果:
Months ["Apr", "Feb", "Mar", "May"]
Countt [4.0, 10.0, 12.0, 5.0]
在这个实体中,我还有monthNumber的属性。
我如何能够打印出按月份编号排序的这些数组?
现在似乎正在按字母顺序排列。
谢谢
答案 0 :(得分:0)
这将完成所要求的:
var results = NSArray()
let appDel = UIApplication.sharedApplication().delegate as! AppDelegate
let context = appDel.managedObjectContext
let fetch = NSFetchRequest(entityName: "Work")
let entity = NSEntityDescription.entityForName("Work", inManagedObjectContext: context)!
let monthDesc = entity.attributesByName["shortMonth"] as NSAttributeDescription!
let monthNumber = entity.attributesByName["month"] as NSAttributeDescription!
let keyPathExpression = NSExpression(forKeyPath: "date")
let countExpression = NSExpression(forFunction: "count:", arguments: [keyPathExpression])
let expressionDescription = NSExpressionDescription()
expressionDescription.name = "count"
expressionDescription.expression = countExpression
expressionDescription.expressionResultType = .Integer32AttributeType
fetch.propertiesToFetch = [monthDesc, monthNumber, expressionDescription]
fetch.propertiesToGroupBy = [monthDesc, monthNumber]
let sortDescriptor = NSSortDescriptor(key: "month", ascending: true)
let sortDescriptors = [sortDescriptor]
fetch.sortDescriptors = sortDescriptors
fetch.resultType = .DictionaryResultType
fetch.returnsObjectsAsFaults = false;
do {
results = try context.executeFetchRequest(fetch)
} catch {
print("Unable to fetch results")
abort()
}
let months = results.flatMap{$0["shortMonth"] as? String}
let countt = results.flatMap{$0["count"] as? Double}
print("Months \(months)")
print("Countt \(countt)")
这将按monthNumber和monthName分组,并按monthNumber排序并输出monthName和count。
输出:
Months ["Jan", "Feb", "Mar", "Apr"]
Countt [3.0, 10.0, 3.0, 10.0]