当然,您可以只将谓词和排序描述符应用于关系返回的集合。如果集合相对较小(因为它是在内存中完成的,所有对象都必须被获取),那么简单且非常快。您可能希望预先执行该批处理以限制执行 I/O 的次数。
根据数据库的大小和经理(以及索引)下的员工数量,您可能希望在数据库级别完成所有操作......
// We want "Employee" objects
NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"Employee"];
// Assuming the "inverse" relationship from employee-to-manager is "manager"...
// We want all employees that have "our" manager, and a salary > 10000
fetchRequest.predicate = [NSPredicate predicateWithFormat:@"(manager == %@) AND (salary > 10000", manager];
// Sort all the matches by salary, little-to-big
fetchRequest.sortDescriptors = [NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:@"salary" ascending:YES]];
// Limit the returned set to 1 object, which will be the smallest
fetchRequest.fetchLimit = 1;
这将在数据库级别执行整个查询,并且只返回 1 个对象。
As always, performance issues are usually highly dependent on your model layout, and the options used for specifying the model and its relationships.