IOS:UISerachBar过滤器名称,但不包含与之相关的ID

时间:2017-07-07 12:17:28

标签: ios objective-c nsarray nsdictionary

我的格式为JSON Dict

{
  "382" : "sudhir kumar",
  "268" : "David  ",
  "385" : "aayush test",
  "261" : "Mike watson",
  "277" : "TestDrivers Driver",
  "381" : "sudhir kumar",
  "380" : "sudhir kumar",
  "383" : "asdfgh asdfgh",
  "376" : " "
}

我必须在UISearchBar中显示它。有人请帮我解决这个问题,因为当我从搜索中选择任何名称时,也会选择其ID

我使用以下代码过滤了名称,但没有使用名称为

的相关ID

我的代码是:

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText;
{
    tempArray = [NSArray arrayWithArray:DriverNameArray];
    //NSString *stringToSearch = textField.text;

    tempId = [NSArray arrayWithArray:DriverIdArray];

    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF BEGINSWITH[c] %@",searchText]; // if you need case sensitive search avoid '[c]' in the predicate

    //NSPredicate * predicateid = [NSPredicate predicateWithFormat:@"SELF BEGINSWITH[c] %@",stringToSearch];

    NSArray *tempresults = [DriverNameArray filteredArrayUsingPredicate:predicate];
    if (tempresults.count > 0)
    {
        tempArray = [NSArray arrayWithArray:tempresults];
        tempId = [NSArray arrayWithArray:tempresults];
    }
    [SEarchTable reloadData];
    //return  YES;
}

它始终为所有已过滤的名称返回相同的ID

2 个答案:

答案 0 :(得分:0)

创建包含ID和名称

NSarray NSdictionary
MasterArray :

(
 0{ id = "382" , drivername = "sudhir kumar"}
 1{ id = "383" , drivername = "sudha mishra"}
.
.
 n{ id = "384" , drivername = "sudesh pandit"}
)

您在DriverNameArray中获得的任何搜索结果。迭代循环,并将驱动程序名称与MasterArray进行比较 :

for(i = 0; i< DriverNameArray.count , i++)
{
    //take driver name from search result array
    NSString * driverName = [DriverNameArray objectAtIndex:i];
    for(j = 0; j< MasterArray.count , j++){// search driver name in MasterArray
        NSDictionary *driverInfoDic = [MasterArray objectAtIndex:j];
        if(driverName isEqualToString:[driverInfoDic objectForKey:@"drivername"])
            NSString *driverId = [driverInfoDic objectForKey:@"Id"];//use this driver id by storing it in DiverIdArray
    }
}

答案 1 :(得分:0)

您只过滤了Drivers'names数组,该数组主要与Drivers'ids数组无关。我建议你加入id,并将其命名为字典并将其存储在一个数组中。因此,无论何时使用name或id过滤它,其余信息都将存储在一个对象中

@property (nonatomic, strong) NSMutableArray *allElements
@property (nonatomic, strong) NSArray *filteredArray;

`

  for (int i=0; i < 10; i++) { //Just simple example
        NSDictionary *dictionary = @{@"name": DriverNameArray[i], @"id": DriverIdArray[i] };
        [self.allElements addObject:dictionary];

    }

在您的搜索栏委托中,您可以使用:

NSArray *copyArray = [self.allElements copy];

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name BEGINSWITH %@", searchText];

NSArray *filteredArray = [copyArray filteredArrayUsingPredicate:predicate];


self.filteredArray = filteredArray;

[self.tableView reloadData];