Database Reference
In-Depth Information
let expressionDescription = NSExpressionDescription ()
expressionDescription. name = "headCount"
//2
expressionDescription. expression =
NSExpression (forFunction: "count:" ,
arguments:[ NSExpression (forKeyPath: "department" )])
//3
let fetchRequest = NSFetchRequest (entityName: "Employee" )
fetchRequest. propertiesToFetch =
[ "department" , expressionDescription]
fetchRequest. propertiesToGroupBy = [ "department" ]
fetchRequest. resultType = .DictionaryResultType
//4
var error: NSError ? = nil
if let fetchResults =
coreDataStack . context . executeFetchRequest (fetchRequest,
error: &error) {
return fetchResults as [[ String : String ]]
} else {
println ( "ERROR: \(error?. localizedDescription ) " )
return [[ String : String ]]()
}
}
This code still uses a fetch request to populate the department list screen, but it
also takes advantage of an NSExpression . Here's how it works:
1. You create an NSExpressionDescription and name it headCount .
2. You create an NSExpression with the count : function for the department attribute.
3. You create a fetch request with the Employee entity. This time, the fetch request
should only fetch the minimum required properties by using propertiesToFetch .
You only need the department attribute and a calculated property made by the
expression created earlier. The fetch request also groups the results by the
department attribute. You're not interested in the managed object, so the fetch
request return type is DictionaryResultType . This will return an array of
dictionaries, each containing a department name and an employee count—just
what you need!
4. You execute the fetch request.
Now find the following line of code in viewDidLoad :
items = totalEmployeesPerDepartment ()
Search WWH ::




Custom Search