NSSortDescriptor生成ORDER BY`name` ='bob'DESC?

时间:2016-03-14 00:57:36

标签: objective-c core-data nsfetchedresultscontroller nssortdescriptor

在原始SQL中,首先对所有bob进行排序很简单。

如何使用NSFetchedResultsController和NSSortDescriptor执行此操作?

2 个答案:

答案 0 :(得分:0)

我认为你不能用NSSortDescriptor做到这一点,因为这是用于键值排序而不支持表达式。

但是,它可以在NSFetchRequest的帮助下工作。将获取请求的结果类型设置为字典

fetchRequest.resultType = NSDictionaryResultType;

然后,您可以将属性设置为获取所需的属性,并为计算属性添加表达式:

NSExpression *expression = [NSExpression expressionWithFormat:@"name=='bob'"];
NSExpressionDescription *expressionDescription = [NSExpressionDescription new];
expressionDescription.name = "isCalledBob";
expressionDescription.expression = expression;
expressionDescription.resultType = NSBooleanAttributeType;

[fetchRequest propertiesToFetch:@[…, expressionDescription];

然后,您可以在密钥NSSortDescriptor上使用isCalledBob

通过这种方式,您可以获得字典而不是托管对象。

键入Safari,没有测试,我的孩子在几分钟内醒来。

答案 1 :(得分:0)

我发现的解决此问题的方法是添加一个额外的字段来帮助FRC。即isBob,只要设置了名称,它就会更新。