如何使用 NSPredicate 根据子元素进行过滤?

发布于 2024-11-07 18:58:46 字数 405 浏览 0 评论 0原文

我正在使用核心数据;假设我的员工和部门之间是多对一的关系,并且员工存储在每个部门的一个 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

倦话 2024-11-14 18:58:46

首先,您在这里没有有效地使用 Core Data,因为您总是从数据存储中获取所有部门,然后在内存中过滤结果数组。您可以直接查询托管对象上下文以查找匹配的部门,而不是获取所有部门,这可以减少内存消耗,并且如果您有很多部门,速度也可能会更快。

NSManagedObjectContext *moc = ...;
NSFetchRequest *request = [[[NSFetchRequest alloc] init] autorelease];
[request setEntity:[NSEntityDescription entityForName:@"Department" inManagedObjectContext:moc]];
[request setPredicate:[NSPredicate predicateWithFormat:@"employees.@count == 1"]];
NSArray *singleEmployeeDepartments = [moc executeFetchRequest:request error:NULL];

另一个关键部分是在谓词字符串中使用@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.

NSManagedObjectContext *moc = ...;
NSFetchRequest *request = [[[NSFetchRequest alloc] init] autorelease];
[request setEntity:[NSEntityDescription entityForName:@"Department" inManagedObjectContext:moc]];
[request setPredicate:[NSPredicate predicateWithFormat:@"employees.@count == 1"]];
NSArray *singleEmployeeDepartments = [moc executeFetchRequest:request error:NULL];

The other key part is to use the @count operator in the predicate string to query departments that have a specific number of employees.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文