Setting up a CoreData regular expression predicate for a comma-separated list

◇◆丶佛笑我妖孽 提交于 2019-12-12 02:35:08

问题


I'm beating my head against a wall trying to get a regular expression function to work with a CoreData fetch. I have an attribute named maps on an NSManagedObject subclass that I'm trying to filter by. This maps attribute is a string with a list of id values like so:

1,10,12,8

Here's how my predicate is being constructed:

NSString *format = [NSString stringWithFormat: @"(maps matches '.*\\b%@\\b.*')", _map.mapID];
NSPredicate *predicate = [NSPredicate predicateWithFormat:format];
[request setPredicate:predicate];

NSManagedObjectContext *moc = [[RKManagedObjectStore defaultObjectStore] primaryManagedObjectContext];
_resultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:request
                                                         managedObjectContext:moc
                                                           sectionNameKeyPath:@"name.stringGroupByFirstInitial"
                                                                    cacheName:nil];

I built the RegEx using this Rubular example: http://rubular.com/r/zELaz19x0T

The mapID value is an integer as a string.

I've read the other questions on SO about the predicate matching against the entire string, but I feel like that should be handled with this pattern using the .* at the beginning and end of the pattern.

The result of this code always returns zero results. If the predicate is not used, all objects are returned as expected. Can anyone see what the issue is here? Thanks!


回答1:


This is solved with this code:

NSString *format = @"(maps MATCHES %@) OR (maps == '')";
NSString *pattern = [NSString stringWithFormat:@".*(\\b%@\\b).*", _map.mapID];
NSPredicate *predicate = [NSPredicate predicateWithFormat:format, pattern];

I was assuming the format of the predicate was the same as formatting a string, which is not. I was enlightened by this other answer: https://stackoverflow.com/a/12672462/189292



来源:https://stackoverflow.com/questions/17180308/setting-up-a-coredata-regular-expression-predicate-for-a-comma-separated-list

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