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

查看:21
本文介绍了从包含 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".

我能想到这样的事情,

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 的MATCHES"运算符可用于与正则表达式进行比较:

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

但是您还应该考虑将字符串属性替换为与 Page 实体的一对多关系,那么谓词将看起来像

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天全站免登陆