NSPredicate 用于过滤掉另一个集合中的所有项目
有什么办法可以做到这一点吗?我有一组项目想要从另一组中排除。我知道我可以循环遍历集合中的每个项目,并且仅将其添加到我的filteredSet(如果它不在其他集合中),但如果我可以使用谓词,那就太好了。
要排除的项目集不是直接相同类型对象的集合;而是一组相同类型的对象。它是一组字符串;如果其中一个属性与该字符串匹配,我想从我的第一组中排除任何内容......换句话说:
NSMutableArray *filteredArray = [NSMutableArray arrayWithCapacity:self.questionChoices.count];
BOOL found;
for (QuestionChoice *questionChoice in self.questionChoices)
{
found = NO;
for (Answer *answer in self.answers)
{
if ([answer.units isEqualToString:questionChoice.code])
{
found = YES;
break;
}
}
if (!found)
[filteredArray addObject:questionChoice];
}
这可以用谓词来完成吗?
Is there any way to do this? I have a set of items that I want to exclude from another set. I know I could loop through each item in my set and only add it to my filteredSet if it's not in the other set, but it would be nice if I could use a predicate.
The set of items to exclude isn't a set of the same type of object directly; it's a set of strings; and I want to exclude anything from my first set if one of the attributes matches that string.... in other words:
NSMutableArray *filteredArray = [NSMutableArray arrayWithCapacity:self.questionChoices.count];
BOOL found;
for (QuestionChoice *questionChoice in self.questionChoices)
{
found = NO;
for (Answer *answer in self.answers)
{
if ([answer.units isEqualToString:questionChoice.code])
{
found = YES;
break;
}
}
if (!found)
[filteredArray addObject:questionChoice];
}
Can this be done with a predicate instead?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这个谓词格式字符串应该可以工作:
将其与适当的 NSArray 过滤方法结合起来。如果 self.questions 是一个常规的不可变 NSArray,它看起来像
如果它是一个 NSMutableArray,则适当的用法将是
小心最后一个,但它会修改现有数组以适应结果。如果需要,您可以创建数组的副本并过滤该副本以避免这种情况。
参考:
NSArray 类参考
NSMutableArray 类参考
谓词编程指南
This predicate format string should work:
Combine it with the appropriate NSArray filtering method. If
self.questions
is a regular immutable NSArray, it would look something likeIf it's an NSMutableArray, the appropriate usage would be
Be careful with that last one though, it modifies the existing array to fit the result. You can create a copy of the array and filter the copy to avoid that, if you need to.
Reference:
NSArray Class Reference
NSMutableArray Class Reference
Predicate Programming Guide
查看 Apple 给出的使用 带有数组的谓词。它使用filteredArrayUsingPredicate。
Check out the example given by Apple for using predicates with arrays. It employs filteredArrayUsingPredicate.