1

我有一个使用以下字符串构建的谓词

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"displayName == [cd] %@ AND emailAddress == [cd] %@" , displayName, emailAddress];

在运行我的应用程序时,我会定期遇到以下原因的陷阱:

Fatal Exception   NSInvalidArgumentException
unimplemented SQL generation for predicate : (0x64b5580 <x-coredata://3AA31AFB-35E4-468C-876D-03DEB56F38A3/aaa/p14> IN )

看起来问题是由将有效 SQL 注入谓词语句引起的。

这里推荐的解决方法是使用具有以下格式的谓词吗?

[NSPredicate predicateWithFormat:@"(displayName == [cd] \"%@\") AND (emailAddress == [cd] \"%@\")" , displayName, emailAddress];

即用双引号将搜索目标括起来?或者这里推荐其他方法?

4

1 回答 1

5

如果您不确定值的完整性,请尝试使用NSCompoundPredicate. 仅当值有效时才将谓词添加到谓词数组并AND从谓词数组创建复合谓词

NSMutableArray *subPredicates = [NSMutableArray array];

if (displayName) {
    [subPredicates addObject:[NSPredicate predicateWithFormat:@"displayName == [cd] %@",displayName]];
}

if (emailAddress) {
    [subPredicates addObject:[NSPredicate predicateWithFormat:@"emailAddress == [cd] %@",emailAddress]];
}

NSPredicate *compoundPredicate = [NSCompoundPredicate andPredicateWithSubpredicates:subPredicates];
于 2013-07-17T09:25:05.563 回答