基于 SQL 查询创建 NSPredicate

Creating an NSPredicate based off of a SQL Query

我有以下 SQL 需要变成 NSPredicate:

SELECT * FROM accounts
WHERE deleted = NO AND inactive = N0
AND name LIKE 'Harry%'
ORDER BY accounts DESC, sales DESC;

我可以使用 BEGINSWITH 代替 SQL 和 NSPredicate 中的类似方法吗?

NSPredicate 仅对应于 SQL 查询的 WHERE 子句。您可以使用 name = false and inactive = false and name like 'Harry*',或者是的,您可以使用 name BEGINSWITH 'Harry' 而不是类似的。请注意,它使用“?”的 glob 类型通配符。和“*”而不是 SQL 通配符。 https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/Predicates/Articles/pSyntax.html 提供更完整的文档。 NSFetchRequest class 将代表其余子句——指定要获取的实体(FROM 子句)和排序描述符(ORDER BY 子句)以及谓词。

NSString *atributeValue =@“Harry”;
NSPredicate *predicate = [NSPredicate predicateWithFormat:@“deleted == %@ && inactive == %@ && name begindsWith %@ ”, @0,@0,atributeValue];

NSSortDescriptor *descriptor1 = [nssortDescriptor sortDescriptorWithKey:@“accounts”ascending : NO];

NSSortDescriptor *descriptor2 = [nssortDescriptor sortDescriptorWithKey:@“sales”ascending : NO];

NSArray *result = [all filteredArrayUsingPredicate: predicate]sortedArrayUsingDescriptors :[NSArray arrayEithObjects:descriptor1,descriptor2];

希望对你有帮助