Reputation: 11247
Actually am getting datas from JSON webservice. I need to search data from UITableView
cells using uisearchdisplaycontroller
.
I have passed data into cells successfully using NSMutablArray
with multiple array. But now i need to search data from that.
My array:
[
{
"name": "jhon",
"city": "chennai",
}
{
"name": "Micle",
"city": "Newyork",
}
{
"name": "Micle",
"city": "Washigton",
}
]
My custom cells in UITableView:
cell.P_name.text = [details objectForKey:@"name"];
cell.P_city.text = [details objectForKey:@"city"];
In Search i tried :
- (void)filterContentForSearchText:(NSString*)searchText scope:(NSString*)scope
{
//-- Help to customize operations
searchResults = [[NSArray alloc]initWithArray:mainArray];
NSPredicate *resultPredicate = [NSPredicate predicateWithFormat:@"SELF contains[cd] %@", searchText];
searchResults = [details filteredArrayUsingPredicate:resultPredicate];
[tableView reloadData];
}
Can anybody help to resolve my issue.
Upvotes: 1
Views: 822
Reputation: 47099
I just put my logic take one more mutable array in .h file name is _temArray
And add your _mainArray (populated on tableView) to your _temArray such like,
[_temArray addObjectsFromArray:_mainArray];
In Search method use NSPredicate
:
- (void)filterContentForSearchText:(NSString*)searchText scope:(NSString*)scope
{
//-- Help to customize operations
if([searchText length] > 0)
{
NSMutableArray *fileterMainArray = (NSMutableArray *)_temArray
NSPredicate *predicatePeople = [NSPredicate predicateWithFormat:@"name BEGINSWITH[cd] %@", searchText]; // here if you want to search by city then change "name" to "city" at pattern.
NSArray *filteredArray = [fileterMainArray filteredArrayUsingPredicate:predicatePeople];
[_mainArray addObjectsFromArray:filteredArray];
}
else
[_mainArray addObjectsFromArray:_temArray];
[self.tblView reloadData]; // don't forget to reload Table data.
}
Upvotes: 0
Reputation: 119041
You should have 2 arrays:
mainDataList
)dataSourceList
)Initially:
self.dataSourceList = self.mainDataList;
because you are displaying all of the data in your table view. When any search is cancelled you also go back to this state (then reload).
When searching however, you need to filter the contents of the dataSourceList
and reload the table:
- (void)filterContentForSearchText:(NSString*)searchText scope:(NSString*)scope
{
NSPredicate *resultPredicate = [NSPredicate predicateWithFormat:@"name contains[cd] %@", searchText];
self.dataSourceList = [self.mainDataList filteredArrayUsingPredicate:resultPredicate];
[tableView reloadData];
}
NOTE: the above predicate only searches the name
in your dictionaries...
Now, all of your table view methods only use self.dataSourceList
, and you modify its contents based on your state. You code is clean and simple. Smile :-)
Upvotes: 3