Search code examples
swiftcore-datanspredicatepredicate

NSPredicate for searching a string with double quotes


An attribute element in coredata model is a string(json string format), which is an array of dictionaries like below,

one element has

"[{"tagName":"sad","count":2},{“tagName":"happy","count":1}]"

and other has

"[{"tagName":"sad1","count":2},{“tagName":"happy1","count":1},{“tagName":"nothappy","count":1}]"

Need to search the list with refer to the tagname.

If I use the predicate below,

tagName = "sad"
tagNameFilter += String(format: "vrTags CONTAINS[cd] \"%@\"", tagName)

it's returning both elements. It should return the first element alone

If I use without double quotes

tagName = "sad"
tagNameFilter += String(format: "vrTags CONTAINS[cd] %@", tagName)

it's crashing with reason:

unimplemented SQL generation for predicate : (vrTags CONTAINS[cd] sad) (LHS and RHS both keypaths) with userInfo of (null)

If I use

tagName = "sad"
tagNameFilter += String(format: "vrTags CONTAINS[cd] \"\"%@\"\"", tagName)

it's crashing with reason: Unable to parse the format string

How to solve this filter issue? Any suggestions would be appreciated.


Solution

  • In order to search for a string "sad" including the quotation marks you have to pass that string with the quotation marks as an argument to NSPredicate(format:). This can be done with with string interpolation:

    let tagName = "sad"
    let predicate = NSPredicate(format: "vrTags CONTAINS[cd] %@", "\"\(tagName)\"")
    print(predicate) // vrTags CONTAINS[cd] "\"sad\""
    

    And never use String(format:) and string concatenation to build complex predicates. That is very error-prone because the quoting and escaping rules for predicate strings are different from those to format strings.

    If you need to combine multiple conditions with “AND” then do it like

    let p1 = NSPredicate(...)
    let p2 = NSPredicate(...)
    // ...
    let predicate = NSCompoundPredicate(andPredicateWithSubpredicates: [p1, p2, ...])