derdida
derdida

Reputation: 14904

NSPredicate with Swift and Core Data

i have a Core Data Object and i have 2 Fieds (one String(GUID) and one Int which i want to use as Filter)

So in SQL it would be "SELECT * FROM Answers WHERE qIndex = 1 AND GUID = '88bfd206-82fb-4dd0-b65d-096f8902855c'

Ive tried it with Core Data but i am not able to Filter with the String Value.

Here is my Code

    var request = NSFetchRequest(entityName: "Answers")
    request.returnsObjectsAsFaults = false;

    let resultPredicate1 = NSPredicate(format: "qIndex = %i", qIndex)
    let resultPredicate2 = NSPredicate(format: "formUUID = %s", formUUID)

    var compound = NSCompoundPredicate.andPredicateWithSubpredicates([resultPredicate1, resultPredicate2])
    request.predicate = compound


    var results:NSArray = context.executeFetchRequest(request, error: nil)

Any ideas what i am doing Wrong? With the Same Code and Filter for 2 Integer Values it works fine.

Thanks in Advance

Upvotes: 19

Views: 37409

Answers (3)

Glen Low
Glen Low

Reputation: 4497

Instead of worrying about %@ conversions and then composing AND predicates, you can use the PredicatePal framework:

let compound = *(Key("qIndex") == qIndex && Key("formUUID") == formUUID)

Assuming that qIndex and formUUID are the correct type, Swift will automatically deduce the correct types for the Key objects.

Upvotes: 1

DarksteelPenguin
DarksteelPenguin

Reputation: 464

This is not the exact response to your question, but a problem people might now encouter with your code now:

In the latest version of XCode, you must now unwrap the predicate, like this:

var compound = NSCompoundPredicate.andPredicateWithSubpredicates([predicate1!, predicate2!])

because NSPredicate initializer now return NSPredicate? type.

Upvotes: 8

Martin R
Martin R

Reputation: 540055

If formUUID is an NSString or a Swift String then you have to use the %@ placeholder:

let resultPredicate2 = NSPredicate(format: "formUUID = %@", formUUID)

Upvotes: 43

Related Questions