【问题标题】:iOS filtering an arrayiOS过滤数组
【发布时间】:2012-12-04 00:28:40
【问题描述】:
我有一个显示在表格中的数据数组。该数组有多个字段,包括我要过滤的两个特定字段,“呼叫类型”和“县”。 “呼叫类型”的值为“f”或“e”,县的值为“w”或“c”。我想要 4 个 UISwitch 来打开/关闭“w”,打开/关闭“c”等。这很难解释,但如果你去这个网站看看右上角,它到底是什么我想要做。 http://www.wccca.com/PITS/ 在 4 个过滤器中,两个过滤器控制县域,两个过滤器控制呼叫类型字段。但它们都是独立运作的。我将如何实现这一目标?每次过滤某些内容时,我会使用 NSPredicate 创建一个新数组吗?谢谢。
【问题讨论】:
标签:
ios
uitableview
filter
nsarray
nspredicate
【解决方案1】:
您绝对可以为此使用NSPredicate。可能最简单的做法是对所有四个开关使用相同的 IBAction 并让它重新计算:
- (IBAction)anySwitchDidChange:(id)sender
{
// make a set of all acceptable call types
NSMutableSet *acceptableCallTypes = [NSMutableSet set];
if(self.fSwitch.on) [acceptableCallTypes addObject:@"f"];
// ... etc, to create acceptableCallTypes and acceptableCounties
NSPredicate *predicate =
[NSPredicate predicateWithFormat:
@"(%@ contains callType) and (%@ contains county)",
acceptableCallTypes, acceptableCounties];
/*
this predicate assumes your objects have the properties 'callType' and
'county', and that you've filled the relevant sets with objects that would
match those properties via isEqual:, whether strings or numbers or
anything else.
NSDictionaries are acceptable since the internal mechanism used here is
key-value coding.
*/
NSArray *filteredArray = [_sourceArray filteredArrayUsingPredicate:predicate];
// send filteredArray to wherever it needs to go
}
使用predicateWithFormat: 会导致文本被立即解析。在这种情况下,这应该没有任何问题,但一般来说,您可以提前创建谓词并仅在相关时刻提供参数,如果您最终在真正的时间关键区域使用一个参数。