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

非 Y 不嫁゛ 提交于 2019-12-23 12:27:38

问题


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?


回答1:


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?.



来源:https://stackoverflow.com/questions/22767022/ios-nspredicate-string-length-always-evaluates-to-0-when-string-starts-with-ar

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