Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IOS Swift Core Data how to add fields in propertiesToFetch that is not in propertiesToGroupBy

Need help.

I have 4 fields in my table:

  • email
  • message
  • read
  • date_received

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
like image 665
jdoe Avatar asked Mar 20 '15 12:03

jdoe


1 Answers

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
like image 139
Mundi Avatar answered Sep 18 '22 15:09

Mundi