如何使用 NSPredicate 根据子元素进行过滤?
我正在使用核心数据;假设我的员工和部门之间是多对一的关系,并且员工存储在每个部门的一个 NSSet
中。我想找到所有只有一名员工的部门。如何使用核心数据做到这一点?
我尝试了下面的代码,但出现异常,指出 MYEmployee 没有响应 allObjects
。
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"ANY SELF.employees.allObjects.count == 1"];
singleEmployeeDepartments = [[myModelController allDepartments] filteredArrayUsingPredicate:predicate]];
I'm using Core Data; let's say that I have a many-to-one relationship between employees and departments, and employees are stored in an NSSet
in each department. I want to find all the departments that only have one employee. How do I do this with Core Data?
I tried the below code and I get an exception saying that MYEmployee doesn't respond to allObjects
.
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"ANY SELF.employees.allObjects.count == 1"];
singleEmployeeDepartments = [[myModelController allDepartments] filteredArrayUsingPredicate:predicate]];
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
首先,您在这里没有有效地使用 Core Data,因为您总是从数据存储中获取所有部门,然后在内存中过滤结果数组。您可以直接查询托管对象上下文以查找匹配的部门,而不是获取所有部门,这可以减少内存消耗,并且如果您有很多部门,速度也可能会更快。
另一个关键部分是在谓词字符串中使用
@count
运算符来查询具有特定员工数量的部门。First of all, you're not using Core Data efficiently here, because you are always fetching all departments from the data store and then filtering the resulting array in memory. You can query the managed object context directly for matching departments, instead of fetching all departments, which can reduce memory consumption and might also be faster if you have a lot of departments.
The other key part is to use the
@count
operator in the predicate string to query departments that have a specific number of employees.