我有一个显示在表中的数据数组。该数组有多个字段,包括我想要过滤的两个特定字段,"call type“和"county”。"call type“的值是"f”或"e“,县的值是"w”或"c“。我想有4个UISwitch来打开/关闭"w",打开/关闭"c“等。这很难解释,但如果你去这个网站,看看右上角,这正是我想要做的。http://www.wccca.com/PITS/在4个筛选器中,两个筛选器控制县字段,两个筛选器控制呼叫类型字段。但它们都是独立运行的。我该如何去实现这个目标呢?每次过滤某些东西时,我会使用NSPredicate来创建一个新的数组吗?谢谢。
发布于 2012-12-04 08:51:07
为此,您绝对可以使用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:会立即对文本进行解析。在这种情况下,这应该没有任何问题,但通常情况下,您可以提前创建谓词,并仅在相关时刻提供参数,如果您最终在真正的时间关键领域使用了一个谓词。
https://stackoverflow.com/questions/13694216
复制相似问题