Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSPredicate with Swift and Core Data

Tags:

swift

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

like image 863
derdida Avatar asked Jul 20 '14 21:07

derdida


People also ask

What is NSPredicate format in Swift?

NSPredicate is a Foundation class that specifies how data should be fetched or filtered. Its query language, which is like a cross between a SQL WHERE clause and a regular expression, provides an expressive, natural language interface to define logical conditions on which a collection is searched.

What is predicate in core Swift?

For example, if you already completed project 33 you'll have seen how predicates let us find iCloud objects by reference. Put simply, a predicate is a filter: you specify the criteria you want to match, and Core Data will ensure that only matching objects get returned.

What is NSPredicate in Objective C?

CONTAINS operator : It allows to filter objects with matching subset. NSPredicate *filterByName = [NSPredicate predicateWithFormat:@"self. title CONTAINS[cd] %@",@"Tom"]; LIKE : Its simple comparison filter.


2 Answers

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

let resultPredicate2 = NSPredicate(format: "formUUID = %@", formUUID)
like image 133
Martin R Avatar answered Oct 30 '22 05:10

Martin R


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.

like image 43
DarksteelPenguin Avatar answered Oct 30 '22 03:10

DarksteelPenguin