开发者

NSPredicate, whitespaces in CoreData. How to trim in predicate?

开发者 https://www.devze.com 2023-04-12 22:07 出处:网络
I have a CoreData/SQLite application in which I have \"Parent Categories\" and \"Categories\". I do not have control over the data, some of the \"Parent Categories\" values have trailing white spaces.

I have a CoreData/SQLite application in which I have "Parent Categories" and "Categories". I do not have control over the data, some of the "Parent Categories" values have trailing white spaces.

I could use CONTAINS (or I should say it works with CONT开发者_运维知识库AINS but this is something I can not use). For example I have 2 entries, MEN and MENS. If I use CONTAINS I will return both records, you can see how this would be an issue.

I can easily trim on my side, but the predicate will compare that with the database and will not match. So my question is how can I account for whitespaces in the predicate, if possible at all.

I have a category "MENS" which someone has selected in the application, and it is compared against "MENS " in the database.


I would trim the data prior to doing the lookup. You can do this easily usingstringByTrimmingCharactersInSet. By doing it beforehand, you'll also avoid any performance hit. That could be expensive if you're doing a character based comparison withCONTAINS.

So, let's say your search string is "MEN".

Here's the way to strip out any dodgy characters:

NSString *trimmed = [@"MEN  " stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];

There's alsowhitespaceAndNewlineCharacterSetwhich does what it says on the tin.

Alternatively, it's easy to create your own custom character of stuff you want to trim.

For that, have a look at:

NSCharacterSet Class Reference

and

Apple's String Programming Guide

0

精彩评论

暂无评论...
验证码 换一张
取 消