Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CoreData predicate: string property length?

Say if I have an entity Fragment, it has an attribute 'text' which is a string, I want to query the list of Fragment whose text is of length 5:

[NSPredicate predicateWithFormat:@"position == %@ AND text.length == %d", pos, 5];

It does not work (ie returns no result), but if I remove text.length in the query it works and I'm certain that there are texts of length 5, so what do I need to change it to?

Thanks!

like image 427
hzxu Avatar asked Nov 10 '13 11:11

hzxu


2 Answers

There is no length attribute for strings in the NSPredicate. Use regex instead. Your predicate should look as follows:

[NSPredicate predicateWithFormat:@"position == %@ AND text MATCHES %@", pos, @".{5}"];
like image 162
Sviatoslav Yakymiv Avatar answered Nov 18 '22 09:11

Sviatoslav Yakymiv


You cannot use Objective-C functions like length in a Core Data fetch request. But you can replace it with the "LIKE" operator, which does a simple pattern matching:

[NSPredicate predicateWithFormat:@"text LIKE %@", @"?????"];

An interesting point is that Core Data does not throw an exception or return with an error, but just ignores the length method, i.e. it just uses the predicate "text = '5' instead. This can be seen by activating Core Data debug output by setting the launch argument

-com.apple.CoreData.SQLDebug 3

(which is generally a good method to locate Core Data fetch problems).

like image 44
Martin R Avatar answered Nov 18 '22 09:11

Martin R