krish
krish

Reputation: 31

Objective-C predicate for search on comma-separated values

I have values like abc,and,abn which are comma-separated values of a field of an NSManagedObject class. I need an Objective-C predicate which matches this NSManagedObject if the user searches for abc or abd or abn. Also it should search only from beginning of each comma separated value.

Any help in this regard will be helpful.

Upvotes: 0

Views: 850

Answers (2)

pbasdf
pbasdf

Reputation: 21536

Whilst endorsing the general view that you would be better off stripping those strings into their constituent parts before storing them in CoreData, the following should achieve what you want, assuming the attribute in question is name and the string the user is searching for is textToFind:

NSPredicate *predicate = [NSPredicate predicateWithFormat:"name beginswith %@ OR name contains %@", textToFind, [NSString sringWithFormat:",%@", textToFind]];

This will match if the search text is at the beginning or immediately after a "," - amend slightly if there is a space.

Upvotes: 1

Caleb
Caleb

Reputation: 125007

One option is to subclass NSManagedObject and provide a (readonly) property that returns the contents of the property in question as an array instead of a comma separated list. NSString has a -componentsSeparatedByString: method that makes it easy to create such an array.

Another option is to create a predicate that accepts any object that contains the search string in the property in question, and then filter the matching objects to weed out any false positives.

A third possibility is to make sure that the target property always has a comma as the very first character, and then prepend a comma to the search string when you create the predicate. That is, sore a value like ,abc,and,abn instead of abc,and,abn, and then search for ,ab instead of ab.

That said, I think the right solution is to avoid the situation altogether by storing the values as a set rather than as a comma separated list.

Upvotes: 1

Related Questions