从包含id的字符串形式NSPredicate [英] Form NSPredicate from string that contains id's

查看:169
本文介绍了从包含id的字符串形式NSPredicate的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个问题,我不能想到如何写这个谓词。

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

我有一个实体名为Contact,它有一个字符串属性pages ,让我们说

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

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

我的数据库中有很多联系人,我想只提取包含特定ID。所以让我们说,我只想取出这些联系人,哪些页面包含id @1。

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

但是我的问题是,这也会获得联系人,例如有pages = @11,15 。

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!

推荐答案

NSPredicate 可用于与正则表达式进行比较:

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

但是你还应该考虑用一个to-many关系将string属性替换为页面实体,则谓词将类似于

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

这篇关于从包含id的字符串形式NSPredicate的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆