Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
438 views
in Technique[技术] by (71.8m points)

ios - 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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...