Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
864 views
in Technique[技术] by (71.8m points)

core data - Swift - Is there a way to include single quotes (') in a concatenated string?

I have already searched for answers and whatever I tried unfortunately did not work. My case is as follows: I have an array of keywords and I am building an NSPredicate in order to filter data from CoreData. The code below:

var strKeywordsOrFilter = "(1 == 1)" //just an initial {true} statement to assist with the OR conditional
for intIndex in 0...pInputWords.count - 1
{
    let strKeyword = "'" + pInputWords[intIndex] + "'"
    strKeywordsOrFilter = strKeywordsOrFilter + " OR (imageDescr CONTAINS[c] " + strKeyword + ")"
}

imageDescr is one of the entity attributes in my CoreData. What I want to accomplish is to create a concatenated string of OR conditions for as many keywords exist in the array pInputWords. When I debug print the variable strKeywordsOrFilter it does NOT contain any backslashes before any single quote character, e.g.

(1 == 1) OR (imageDescr CONTAINS[c]  'camping') OR (imageDescr CONTAINS[c]  'lake')

but the same variable when it reaches the "predicate" command, it contains backslashes before every single quote, e.g.

(1 == 1) OR (imageDescr CONTAINS[c]  'camping') OR (imageDescr CONTAINS[c]  'lake')

I have tried a number of workarounds but nothing seems to get rid of the "". Any help would be appreciated because I am really stuck!

question from:https://stackoverflow.com/questions/65856362/swift-is-there-a-way-to-include-single-quotes-in-a-concatenated-string

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

No need to manually construct your query, or worry about quotes. You can use a compound predicate instead and standard predicate formatting (%@ for values and %K for keys):

let predicates = pInputWords.map { word in
    NSPredicate(format: "imageDescr CONTAINS[c] %@", word)
}

let finalPredicate = NSCompoundPredicate(orPredicateWithSubpredicates: predicates)

// Which gives:
// imageDescr CONTAINS[c] "camping" OR imageDescr CONTAINS[c] "lake"

ps. Your query string produces the same result when fed to a predicate, which seems to be fine


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...