Form NSPredicate from string that contains id's

余生长醉 提交于 2019-12-29 01:23:11

问题


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!


回答1:


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];


来源:https://stackoverflow.com/questions/14932595/form-nspredicate-from-string-that-contains-ids

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!