2012-12-04 71 views
0

我有一个显示在表中的数据数组。该数组有多个字段,其中包括两个特定的字段,即“呼叫类型”和“县”。 “呼叫类型”的值是“f”或“e”,郡的值是“w”或“c”。我想要有4个UISwitch来打开/关闭“w”,打开/关闭“c”等等。它很难解释,但是如果你去这个网站看右上角,它正是什么我想要做。 http://www.wccca.com/PITS/在4个过滤器中,两个过滤器控制县字段,两个过滤器控制呼叫类型字段。但他们都独立运作。我将如何去完成这件事?我会每次使用NSPredicate创建一个新的数组吗?谢谢。iOS筛选数组

回答

0

你肯定可以使用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:导致文本是正确的那里,然后解析。在这种情况下,应该没有任何问题,但通常情况下,您可以预先创建谓词并在相关时刻仅提供参数,如果您最终在真正时间关键的区域使用该参数。