Ste*_*ser 3 core-data objective-c nspredicate
我正在使用核心数据; 假设我在员工和部门之间存在多对一的关系,员工存储NSSet在每个部门中.我想找到只有一名员工的所有部门.如何使用Core Data执行此操作?
我尝试了下面的代码,我得到一个例外,说MYEmployee没有回应allObjects.
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"ANY SELF.employees.allObjects.count == 1"];
singleEmployeeDepartments = [[myModelController allDepartments] filteredArrayUsingPredicate:predicate]];
Run Code Online (Sandbox Code Playgroud)
首先,您没有在这里有效地使用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];
Run Code Online (Sandbox Code Playgroud)
另一个关键部分是使用@count谓词字符串中的运算符来查询具有特定员工数量的部门.
| 归档时间: |
|
| 查看次数: |
2117 次 |
| 最近记录: |