【问题标题】:How to search From Nsarray in iOS?如何在 iOS 中从 Nsarray 搜索?
【发布时间】:2014-12-27 08:50:59
【问题描述】:

我有 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 视图中使用的数组,并希望根据每个数组键进行搜索,例如 Payment,Payment Date,Status 等。我正在成功搜索所有键,但我认为这不是好方法。我在这里显示我使用的代码。

  - (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 个键,那么我认为这不是好方法。所以请告诉我。

【问题讨论】:

  • 查看NSPredicate
  • 我已经用过这个请在我的搜索委托中看到这个。

标签: ios objective-c iphone uitableview uisearchbar


【解决方案1】:
猜你喜欢
  • 1970-01-01
  • 2014-10-11
  • 2023-03-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多