Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS - NSPredicate string.length always evaluates to 0 when string starts with arithmetic operators + - * /

I have a simple method that uses NSPredicate to return the number of rows where comments.length > 0.

Problem is, I found that when the Comment column starts with + - * or /, the length property always evaluates to 0, and thus the row is excluded from the count.

I opened the table in SQLite browser and verified the column is a VARCHAR. Using a SQLite query to check string length works just fine (LENGTH(ZComments) > 0), so this must be a CoreData issue.

Here is my function...

-(int)getCommentsCount{
    NSFetchRequest *request = [[[NSFetchRequest alloc] init] autorelease];
    [request setIncludesSubentities:YES];
    [request setEntity:[NSEntityDescription entityForName:@"InspectionRecord" inManagedObjectContext:managedObjectContext]];

    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(comments.length > 0)"];
    [request setPredicate:predicate];

    NSError *err;
    NSUInteger count = [managedObjectContext countForFetchRequest:request error:&err];

    //count is ALWAYS 0 if 'comments' starts with + - * or /     WHYYY???      
    return count;
}

I was able to work around this by checking for empty/null string instead of using .length, but I'd really like to know why .length fails when the string starts with certain characters.

Has this happened to anyone?

like image 299
iupchris10 Avatar asked Mar 31 '14 16:03

iupchris10


1 Answers

You cannot use Objective-C functions like length in a Core Data fetch request (and the ".length" part is simply ignored when Core Data translates the fetch request to a SQLite query). But you can simply compare with an empty string instead:

 [NSPredicate predicateWithFormat:@"comment != ''"]

For other queries involving the length, you can use the MATCHES operator with a regular expression as shown here: CoreData predicate: string property length?.

like image 105
Martin R Avatar answered Nov 16 '22 05:11

Martin R