2015-03-20 10 views
8

Hai bisogno di aiuto.IOS Swift Core Dati su come aggiungere campi in propertiesToFetch che non è in propertiesToGroupBy

ho 4 campi in mio tavolo:

  • email
  • messaggio
  • leggere
  • date_received

voglio selezionare l'e-mail, messaggio (recente), date_received e la somma dei messaggi non letti

Ecco il risultato previsto:

[email protected] | Messaggio di prova | 2015-02-27 | 28 [email protected] | Prova messaggio2 | 2015-02-29 | 2

Ecco il mio codice corrente:

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)! 

uscita:

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 
+0

favore abilitare [SQL query logging] (http://stackoverflow.com/questions/6428630/xcode4-and-core-data-how-to-enable-sql-debugging) e pubblicare la query risultante. – ctietze

+0

Penso che il tuo problema sia lo stesso di questo: http://stackoverflow.com/questions/20995405/how-to-apply-group-by-clause-in-core-data – sheisd

risposta

1

Basta recuperare i messaggi con il solito NSManagedObjectResultType (non c'è bisogno di specificare che). Poi basta ottenere il conteggio tramite un KVC (entrambe le soluzioni testate):

let count = (result.filteredArrayUsingPredicate(
    NSPredicate(format: "read = NO")) as NSArray).count 

Un modo non standard ma forse più concisa è quello di sfruttare il fatto che booleani vengono memorizzati come uno e zero

let count = result.count - result.valueForKeyPath("@sum.read")!.integerValue