Christian Schlensker
Christian Schlensker

Reputation: 22478

NSPredicate for fetching keywords that are in a string

In core data I have an entity called keyword with a property 'text'. I want to find all keyword objects that are contained in a particular sting.

I tried:

[NSPredicate predicateWithFormat:@"%@ contains[c] text", myString];

But that crashes. It seems like if it will only work if it's reversed.

Upvotes: 4

Views: 920

Answers (2)

Rotten
Rotten

Reputation: 742

I think you're doing in reverse direction.

Try this.

[NSPredicate predicateWithFormat:@"text contains[cd] %@", myString];

Upvotes: 0

Jason Coco
Jason Coco

Reputation: 78353

The predicate works on the entity, so you have your predicate reversed. Since your entity's text property contains a single word, you'd split the string into multiple words and then test:

// This is very simple and only meant to illustrate the property, you should
// use a proper regex to divide your string and you should probably then fold
// and denormalize the components, etc.
NSSet* wordsInString = [NSSet setWithArray:[myString componentsSeparatedByString:@" "]];
NSPredicate* pred = [NSPredicate predicateWithFormat:@"SELF.text IN %@", wordsInString];

Upvotes: 3

Related Questions