问题描述
我有一个简单的方法,使用NSPredicate返回的行数,其中comments.length> 0。
I have a simple method that uses NSPredicate to return the number of rows where comments.length > 0.
问题是,用+ - *或/,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.
我在SQLite浏览器中打开表,列是一个VARCHAR。使用SQLite查询来检查字符串长度是否正常(LENGTH(ZComments)> 0),因此这必须是一个CoreData问题。
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.
-(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;
}
我可以通过检查空/空字符串而不是使用.length,但是我真的想知道为什么当字符串以某些字符开头时.length失败。
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.
这是发生在任何人吗?
推荐答案
您不能在Core Data fetch请求中使用 length
$ b(当Core Data将获取请求
转换为SQLite查询时,将忽略.length部分)。但是你可以简单地比较一个空字符串:
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 requestto a SQLite query). But you can simply compare with an empty string instead:
[NSPredicate predicateWithFormat:@"comment != ''"]
对于涉及长度的其他查询,可以使用MATCHES运算符与
a正则表达式:。
For other queries involving the length, you can use the MATCHES operator witha regular expression as shown here: CoreData predicate: string property length?.
这篇关于iOS - 当字符串以算术运算符开始时,NSPredicate string.length总是计算为0 - * /的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!