2016-02-08 4 views
18

Derzeit habe ich eine einfache NSFetchRequest mit einem zugehörigen NSPredate. Ich hoffe jedoch, dass es eine Möglichkeit gibt, mehrere Prädikate anzuhängen. Ich habe Beispiele in Objective C gesehen, aber keine für Swift.Mehrere NSPredicates für NSFetchRequest in Swift?

Können Sie eine Liste von NSPredicates definieren oder mehrere NSPredate-Objekte an ein einzelnes NSFetchRequest anfügen?

Danke!

+2

die API ist das gleiche, so dass die Beispiele, die Sie gelten gesehen haben - probieren Sie es und angezeigten Code ein, wenn Sie ein Problem – Wain

Antwort

31

Sie können "NSCompoundPredicate" verwenden. Zum Beispiel:

let converstationKeyPredicate = NSPredicate(format: "conversationKey = %@", conversationKey) 
    let messageKeyPredicate = NSPredicate(format: "messageKey = %@", messageKey) 
    let andPredicate = NSCompoundPredicate(type: NSCompoundPredicateType.AndPredicateType, subpredicates: [converstationKeyPredicate, messageKeyPredicate]) 
    request.predicate = andPredicate 

Sie in "AndPredicateType" ändern oder "OrPredicateType"

+0

Aber was, wenn messageKeyPredicate in diesem Beispiel haben, besteht nur in bestimmten Situationen. Gibt es eine elegante Möglichkeit, Spagetti-Code beim Versuch zu vermeiden, das NSCompoundPredicate zu konstruieren? – ardevd

+0

Nevermind, nur eine Liste von NSPredicates erstellen ist in Ordnung! Vielen Dank! – ardevd

+0

Können wir andPredicate verwenden - oder was ist der Unterschied? let andPredicate = NSCompoundPredicate (undPredicateWithSubpredicates: [predicateIsNumber, predicateIsEnabled]) – davidrynn

5

Update für Swift 4

 let predicateIsNumber = NSPredicate(format: "isStringOrNumber == %@", NSNumber(value: false)) 
     let predicateIsEnabled = NSPredicate(format: "isEnabled == %@", NSNumber(value: true)) 
     let andPredicate = NSCompoundPredicate(type: NSCompoundPredicate.LogicalType.and, subpredicates: [predicateIsNumber, predicateIsEnabled]) 

     //check here for the sender of the message 
     let fetchRequestSender = NSFetchRequest<NSFetchRequestResult>(entityName: "Keyword") 
     fetchRequestSender.predicate = andPredicate 

Die Änderung der neuesten Swift Version ist:

NSCompoundPredicateType.AndPredicateType replaced by `NSCompoundPredicate.LogicalType.and ` 

Hoffe es hilft !!!

Dank

Verwandte Themen