2015-04-04 62 views
2

例如,我的应用程序有两个实体:Department < --- >>Employee。我想获取一个employee对象,该对象在特定对象中具有最大值。 salaryEmployee上的一个属性。使用max属性值以及使用nspredicate的一个关系获取实体

我尝试下面的代码:

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"department == %@ && salary == max(salary)", self.department]; 

但是,没有任何一个对象返回。

使用nspredicate完成此任务的最有效和最正确的方法是什么?

任何人都可以帮到我吗?谢谢。

+0

你有什么错误吗? – Wain 2015-04-04 08:03:01

回答

0

您应该修改谓词以仅过滤部门,但随后使用排序描述符按工资降序对结果进行排序。然后将提取限制设置为1,因此您只能获得薪水最高的员工:

NSFetchRequest *fetch = [NSFetchRequest fetchRequestWithEntityName:@"Employee"]; 
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"department == %@", self.department]; 
NSSortDescriptor *salarySort = [NSSortDescriptor sortDescriptorWithKey:@"salary" ascending:NO]; 
fetch.sortDescriptors = @[salarySort]; 
fetch.fetchLimit = 1; 
+0

谢谢,这种方式应该工作!但我不能确定它是在核心数据上进行这种查询的有效方式,因为我的应用程序有大量数据集。 – 2015-04-04 08:16:12

0

一个有效的解决方案是仅使用关系而不是提取请求。核心数据在后台进行优化,因此您无需担心性能或内存问题。

Employee *highestPaid = [department.employees sortedArrayUsingSortDescriptors: 
    @[[NSSortDescriptor sortDescriptorWithKey:@"salary" ascending:NO]]].firstObject 
相关问题