Need help.
I have 4 fields in my table:
I want to select the email , message (recent) ,date_received, and the sum of unread messages
Here's my expected result:
[email protected] | Test Message | 2015-02-27 | 28 [email protected] | Test Message2 | 2015-02-29 | 2
Here's my current code:
let fetchRequest:NSFetchRequest = NSFetchRequest()
if let entityDescription:NSEntityDescription = NSEntityDescription.entityForName("Message", inManagedObjectContext: managedObjectContext){
fetchRequest.entity = entityDescription
}
fetchRequest.propertiesToFetch = ["email","message","read","date_received"]
fetchRequest.propertiesToGroupBy = ["email"]
fetchRequest.resultType = .DictionaryResultType
fetchRequest.returnsObjectsAsFaults = false
let items:NSArray = managedObjectContext .executeFetchRequest(fetchRequest, error: nil)!
Output:
20 18:24:51.639 JPtxt[33368:1345477] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'SELECT clauses in queries with GROUP BY components can only contain properties named in the GROUP BY
Just fetch the messages with the usual NSManagedObjectResultType
(you don't need to specify that). Then just get the count via a KVC (both solutions tested):
let count = (result.filteredArrayUsingPredicate(
NSPredicate(format: "read = NO")) as NSArray).count
A non-standard but perhaps more concise way is to exploit the fact that booleans are stored as ones and zeros
let count = result.count - result.valueForKeyPath("@sum.read")!.integerValue
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With