Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Core Data - NSPredicate to filter out empty string working incorrect

Tags:

I've been using core data in my project for a while. Few days ago, I find that some of the records saved in database are not showing up in application UI. I've tracked it down and found that they're not being fetched at all when I filter out empty string using NSPredicate. And all of them starts with non-alphabetic characters.

To clarify the problem, I created a sample project and added a few sample data into database. Let's say they are "Sample", "+ sample", "Sample +".

Here's the code snippet I used to filter out empty string. "text" is the name of string property, and moc is NSManagedObjectContext instance.

NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:@"BasicEntity"];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"text.length > 0"];
[request setPredicate:predicate];

NSArray *samples = [moc executeFetchRequest:request error:&error];

Result array contains only 2 entities, which are "Sample" and "Sample +".

I even tried same predicate(of course, using self.length instead of text.length) on simple array containing above sample strings, and I get all 3 correctly.

I wonder if anybody experienced same issue. Or am I missing something in using Core Data? Tested on iOS 7.0.3 simulator & 7.0.6 iPad Air.


UPDATE:As answered in another thread, I solved this issue by using regular expression.

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"text MATCHES %@", @".{1,}"];

Still, I believe original predicate I used is a valid one. I'll file a bug to Apple to get their opinions.

like image 217
Wonjae Avatar asked Feb 27 '14 23:02

Wonjae


1 Answers

This is what you want

[NSPredicate predicateWithFormat:@"%K != %@", @"text", @""]

If you also need to check for nil / NULL do this:

[NSPredicate predicateWithFormat:@"%K != NULL && %K != %@", @"text", @"text", @""]
like image 173
Daniel Eggert Avatar answered Sep 23 '22 01:09

Daniel Eggert