2014-10-31 52 views
0

我有NSarray,我想搜索根据我的数组中的所有键。我已应用此代码。首先这是我的阵列。如何在iOS中搜索Nsarray?

MyArray =  (
      { 
     Payment = "PAY-0172595"; 
     "Payment Date" = "2014-10-29"; 
     "Payment ID" = a1Wo00000011uMMEAY; 
     Status = Paid; 
     "Total Amount" = "217.76"; 
    }, 
      { 
     Payment = "PAY-0177591"; 
     "Payment Date" = "2014-10-30"; 
     "Payment ID" = a1Wo00000011w7uEAA; 
     Status = Paid; 
     "Total Amount" = "100.00"; 
    } 
) 

在上述我展示例如阵列的索引少现在这是阵列是我在UItable视图中使用,并希望像付款,付款日期,状态根据每个阵列钥匙搜索等。我搜索成功关于所有密钥,但我认为这不是好方法。我在这里显示代码是我用过的。

- (void)viewDidLoad 
    { 

    for (int i=0; i<Payments_details.count; i++) 
    { 


    NSString *str=[NSString stringWithFormat:@"%@/%@/%@/%@/%@",[[Payments_details objectAtIndex:i] valueForKey:@"Payment"],[[Payments_details objectAtIndex:i] valueForKey:@"Total Amount"],[[Payments_details objectAtIndex:i] valueForKey:@"Payment Date"],[[Payments_details objectAtIndex:i] valueForKey:@"Status"],[[Payments_details objectAtIndex:i] valueForKey:@"Payment ID"]]; 

    NSDictionary *dict=[[NSDictionary alloc]initWithObjectsAndKeys:str,@"SN", nil]; 

    [search_arr addObject:dict]; 

} 

} 

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText 
{ 
if (![search_bar.text isEqualToString:@""]) 
{ 

    searching=YES; 

    NSPredicate *resultPredicate = [NSPredicate 
            predicateWithFormat:@"SELF contains[cd] %@", 
            searchBar.text]; 
    // NSLog(@"tim %@",resultPredicate); 
    searchArr = [[search_arr valueForKey:@"SN"] filteredArrayUsingPredicate:resultPredicate]; 
    NSLog(@"tim %@",searchArr); 

} 
else 
{ 
    searching=NO; 

} 
[table_Payments reloadData]; 

} 

此代码成功地工作,但假设,当我们搜索像PAY-0177 ....在我的数组这一个第二个指标,现在根据搜索我们需要做这个第一指标。所以我这样做也成功了,这里是我的代码。我在这里显示的代码较少。所以请忽略所有的东西。

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath: (NSIndexPath *)indexPath 
{ 
    if (searching==YES) 
    { 

     NSArray* foo = [[searchArr objectAtIndex:indexPath.row] componentsSeparatedByString: @"/"]; 

     custom_cell.Payment.text = [foo objectAtIndex: 0]; 

     custom_cell.Totalamount.text=[foo objectAtIndex: 1]; 

     custom_cell.PaymentDate.text=[foo objectAtIndex: 2]; 

     custom_cell.Status.text=[foo objectAtIndex: 3]; 


    } 

} 

根据这我得到特定的索引,我想要的。但我认为我的数组中只有四个键现在假设如果我有10个我们的15个键,那么我认为这是不好的方法。所以请告诉我。

+0

查找到[NSPredicate](https://developer.apple.com/librarY/mac/documentation/可可/参考/基金/班/ NSPredicate_Class/index.html的)。 – Michael 2014-10-31 05:11:00

+0

我已经使用过这个请在我的搜索代理中查看。 – rahul 2014-10-31 05:17:54

回答