Search code examples
iosobjective-ccore-datanspredicatensfetchrequest

Form NSPredicate from string that contains id's


I have this problem where I can't think of how to write this predicate.

I have an Entity called Contact, it has a string property "pages", let's say

contact.pages = @"1,5,11,15,17";

There is a lot of contacts in my database, and I want to fetch only these contacts that contains a certain id. So let's say I want to fetch only these contacts, which pages contains id @"1".

I can think of something like this,

NSPredicate* predicate = [NSPredicate predicateWithFormat:@"self.pages CONTAINS %@", _pageId];

But my problem is that this would also get contacts, that e.g has pages = @"11,15".

So any ideas on how to achieve that? I would be grateful for any suggestions, thanks in advance!


Solution

  • The "MATCHES" operator of NSPredicate can be used to compare against a regular expression:

    NSString *pageId = @"1";
    NSString *regex = [NSString stringWithFormat:@"(.*,)?%@(,.*)?", pageId];
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"pages MATCHES %@", regex];
    

    But you should also consider to replace the string property by a to-many relationship to a Page entity, then the predicate would look like

    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"ANY pages.pageid == %@", pageId];