search array in Russian - ios

I made a list in tableviewcontroller, then add search bar and search display. But due to the fact that I have an array in Russian language search is not working. If I add the numbers in the array and start search it's work. But if on the Russian letters, no. How to fix it?
My code
- (instancetype)initWithCoder:(NSCoder *)coder
{
self = [super initWithCoder:coder];
if (self) {
_items
= [NSArray arrayWithObjects:
#"А",
#"Ак",
#"Ба",
#"Бо",
#"22",
#"23",
nil];
}
return self;
}
#pragma mark - UISearchDisplayDelegate
// register a cell reuse identifier for the search results table view
-(void)searchDisplayController:(UISearchDisplayController *)controller
didLoadSearchResultsTableView:(UITableView *)tableView {
[tableView registerClass:[UITableViewCell class]
forCellReuseIdentifier:#"SearchResultsTableViewUITableViewCell"];
}
// perform the search
-(BOOL)searchDisplayController:(UISearchDisplayController *)controller
shouldReloadTableForSearchString:(NSString *)searchString {
NSPredicate *predicate
= [NSPredicate predicateWithFormat:#"self beginswith %#", searchString];
NSArray *searchResults
= [[self items] filteredArrayUsingPredicate:predicate];
[self setSearchResults:searchResults];
return YES;
}
#pragma mark - UITableViewDataSource
// check if displaying search results
-(NSInteger)tableView:(UITableView *)tableView
numberOfRowsInSection:(NSInteger)section {
if ([[self searchDisplayController] isActive]) {
return [[self searchResults] count];
} else {
return [[self items] count];
}
}
// check if displaying search results
-(UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath {
if ([[self searchDisplayController] isActive]) {
UITableViewCell *cell
= [tableView dequeueReusableCellWithIdentifier:#"SearchResultsTableViewUITableViewCell"
forIndexPath:indexPath];
id item = [[self searchResults] objectAtIndex:[indexPath row]];
[[cell textLabel] setText:item];
return cell;
} else {
UITableViewCell *cell
= [tableView dequeueReusableCellWithIdentifier:#"UITableViewCell"
forIndexPath:indexPath];
id item = [[self items] objectAtIndex:[indexPath row]];
[[cell textLabel] setText:item];
return cell;
}
}
#pragma mark - UITableViewDelegate
// manually perform detail segue after selecting a search result
-(void)tableView:(UITableView *)tableView
didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
if ([[self searchDisplayController] isActive]) {
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
[self performSegueWithIdentifier:#"detailSegue" sender:cell];
}
}
#pragma mark - UIViewController
/* prepare for detail scene segue
called after cell selection in the master and
search results table views */
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
UITableViewCell *cell = (UITableViewCell *)sender;
id item = nil;
if ([[self searchDisplayController] isActive]) {
NSIndexPath *indexPath
= [[[self searchDisplayController] searchResultsTableView] indexPathForCell:cell];
item = [[self searchResults] objectAtIndex:[indexPath row]];
} else {
NSIndexPath *indexPath
= [[self tableView] indexPathForCell:cell];
item = [[self items] objectAtIndex:[indexPath row]];
}
UIViewController *detail
= (UIViewController *)[segue destinationViewController];
[[detail navigationItem] setTitle:item];
}
#end

NSPredicate *predicate = [NSPredicate predicateWithFormat:#"SELF contains [cd] %#", self.searchBar.text];
self.searchResults = [[_actualItems filteredArrayUsingPredicate:predicate] mutableCopy];

Related

How should I use searchController

How should I use search controller instead of searchDisplayController in tableView method
I have an example code here
if (tableView == self.searchDisplayController.searchResultsTableView)
Hhere I am getting error on this line it says searchDisplayController is deprecated.
#implementation LocationsViewController
{
NSArray *_park;
}
- (void)viewDidLoad {
[super viewDidLoad];
self.searchResult = [NSMutableArray arrayWithCapacity:[self->_park count]];
// Create a new JSONLoader with a local file URL
JSONLoader *jsonLoader = [[JSONLoader alloc] init];
NSURL *url = [[NSBundle mainBundle] URLForResource:#"park" withExtension:#"json"];
// Load the data on a background queue...
// As we are using a local file it's not really necessary, but if we were connecting to an online URL then we'd need it
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
_park = [jsonLoader locationsFromJSONFile:url];
// Now that we have the data, reload the table data on the main UI thread
[self.tableView performSelectorOnMainThread:#selector(reloadData) withObject:nil waitUntilDone:YES];
});
}
//Just before showing the LocationDetailViewController, set the selected Location object
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
LocationDetailViewController *vc = segue.destinationViewController;
NSIndexPath *indexPath = [self.tableView indexPathForCell:sender];
vc.location = [_park objectAtIndex:indexPath.row];
}
#pragma mark - Table View Controller Methods
//UISearchController *searchController = [[UISearchController alloc] initWithSearchResultsController:nil];
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"LocationCell"];
Location *location = [_park objectAtIndex:indexPath.row];
cell.textLabel.text = location.name;
cell.detailTextLabel.text = location.address;
// cell.detailTextLabel.text = location.ide;
cell.imageView.image = [UIImage imageNamed:#"location_image"];
///////////////////
if (tableView == self.searchDisplayController.searchResultsTableView)
{
cell.textLabel.text = [self.searchResult objectAtIndex:indexPath.row];
}
else
{
cell.textLabel.text = self->_park[indexPath.row];
}
/////////////////
return cell;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
//////////////////////////////////////////////
if (tableView == self.searchDisplayController.searchResultsTableView)
{
return [self.searchResult count];
}
else
{
return [self->_park count];
}
//////////////////////////////////////////////
return [_park count];
}
/////////////////////////////////////////////////
- (void)filterContentForSearchText:(NSString*)searchText scope: (NSString*)scope
{
[self.searchResult removeAllObjects];
NSPredicate *resultPredicate = [NSPredicate predicateWithFormat:#"SELF contains[c] %#", searchText];
self.searchResult = [NSMutableArray arrayWithArray: [self->_park filteredArrayUsingPredicate:resultPredicate]];
}
-(BOOL)searchDisplayController:(UISearchController *)controller shouldReloadTableForSearchString:(NSString *)searchString
{
[self filterContentForSearchText:searchString scope: [[self.searchDisplayController.searchBar scopeButtonTitles] objectAtIndex:[self.searchDisplayController.searchBar selectedScopeButtonIndex]]];
return YES;
}
#end
I believe you have declared a UISearchController by passing nil as a parameter to searchResultsController. So your same tableView is being used as searchResultsController of UISearchController
like
let searchController = UISearchController(searchResultsController: nil)
or
UISearchController searchController = [[UISearchController alloc] initWithSearchResultsController:nil];
I hope all you want to do now is to distinguish whether UISeacrhController is active or it's your tableView so that you can show different cell for them :)
If so,
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"LocationCell"];
Location *location = [_park objectAtIndex:indexPath.row];
cell.textLabel.text = location.name;
cell.detailTextLabel.text = location.address;
// cell.detailTextLabel.text = location.ide;
// cell.imageView.image = [UIImage imageNamed:#"location_image"];
if (searchController.active)
{
cell.textLabel.text = [self.searchResult objectAtIndex:indexPath.row];
}
else
{
cell.textLabel.text = self->_park[indexPath.row];
}
/////////////////
return cell;
}
My answer in comment if (tableView == self.yourSearchController. searchResultsController) would have worked if you had instantiated a different tableView controller and provided as SearchResultsController for UISearchController
But because you have specified nil in your init of UISearchControllersame tableView instance will be used as SearchResultsController. So comparing will result in always yes :)
Rather, you can depend on active property of UISearchController and check in what context tableView is being used and handle it appropriately :)
Hope I made my point clear :) Happy coding :)

UISearchDisplayController - results exists but are not displayed

I have strange problem with UISearchDisplayController.
My code is following:
numberOfRowsInSection:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if ([[self searchDisplayController] isActive])
{
return [self.itemsFound count];
} else {
return [self.items count];
}
return [self.items count];
}
cellForRowAtIndexPath:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
FavouriteTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (!cell)
{
cell = [[FavouriteTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
Facilities *f = nil;
if ([[self searchDisplayController] isActive])
{
f = [self.itemsFound objectAtIndex:indexPath.row];
} else {
f = [self.items objectAtIndex:indexPath.row];
}
[cell.favouriteButton addTarget:self action:#selector(toggleFavourite:) forControlEvents:UIControlEventTouchUpInside];
[cell.titleLabel setText:f.name];
return cell;
}
next:
- (void)filterContentForSearchText:(NSString*)searchText scope:(NSString*)scope
{
NSPredicate *resultPredicate = [NSPredicate predicateWithFormat:#"name contains[c] %#",searchText];
self.itemsFound = [self.items filteredArrayUsingPredicate:resultPredicate];
}
shouldReloadTableForSearchString:
- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString {
self.itemsFound = nil;
[self filterContentForSearchText:searchString
scope:[[self.searchDisplayController.searchBar scopeButtonTitles]
objectAtIndex: [self.searchDisplayController.searchBar
selectedScopeButtonIndex]]];
return YES;
}
My table:
If I type letters, which are on the list:
Results exist but are not showing on a list.
On next picture there are no results and the screen shows correct info.
I have no idea why I can not show results on second screen while results are (displayed on console).
Do you have any idea ?
Thanks for your time.

Can't do a substring operation with something that isn't a string

I have a database with core data and i am trying to make it searchable. It doesn't work and returns this error:
'Can't do a substring operation with something that isn't a string
(lhs = (entity: Device; id: 0x8c63bc0
; data:
{.......}
So that is my code for creating cells.
- (NSManagedObjectContext *)managedObjectContext {
NSManagedObjectContext *context = nil;
id delegate = [[UIApplication sharedApplication] delegate];
if ([delegate performSelector:#selector(managedObjectContext)]) {
context = [delegate managedObjectContext];
}
return context;
}
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
self.searchResults = [[NSArray alloc]init];
[super viewDidLoad];
// Uncomment the following line to preserve selection between presentations.
// self.clearsSelectionOnViewWillAppear = NO;
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem;
}
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
// Fetch the devices from persistent data store
NSManagedObjectContext *managedObjectContext = [self managedObjectContext];
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:#"Device"];
self.devices = [[managedObjectContext executeFetchRequest:fetchRequest error:nil] mutableCopy];
[self.tableView reloadData];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
// Return the number of sections.
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if (tableView == self.searchDisplayController.searchResultsTableView) {
return [self.searchResults count];
}
else
{
return [self.devices count];
}
// Return the number of rows in the section.
// return self.devices.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
if (tableView == self.searchDisplayController.searchResultsTableView) {
NSManagedObject *device = [self.searchResults objectAtIndex:indexPath.row];
[cell.textLabel setText:[NSString stringWithFormat:#"%#", [device valueForKey:#"text1"]]];
[cell.detailTextLabel setText:[device valueForKey:#"text3"]];
}
else
{
// Configure the cell...
NSManagedObject *device = [self.devices objectAtIndex:indexPath.row];
[cell.textLabel setText:[NSString stringWithFormat:#"%#", [device valueForKey:#"text1"]]];
[cell.detailTextLabel setText:[device valueForKey:#"text3"]];
}
return cell;
}
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
// Return NO if you do not want the specified item to be editable.
return YES;
}
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
NSManagedObjectContext *context = [self managedObjectContext];
if (editingStyle == UITableViewCellEditingStyleDelete) {
// Delete object from database
[context deleteObject:[self.devices objectAtIndex:indexPath.row]];
NSError *error = nil;
if (![context save:&error]) {
NSLog(#"Can't Delete! %# %#", error, [error localizedDescription]);
return;
}
// Remove device from table view
[self.devices removeObjectAtIndex:indexPath.row];
[self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
}
}
#pragma mark - Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
// Navigation logic may go here. Create and push another view controller.
/*
<#DetailViewController#> *detailViewController = [[<#DetailViewController#> alloc] initWithNibName:#"<#Nib name#>" bundle:nil];
// ...
// Pass the selected object to the new view controller.
[self.navigationController pushViewController:detailViewController animated:YES];
*/
}
#pragma mark - Segue
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([[segue identifier] isEqualToString:#"UpdateJob"]) {
NSManagedObject *selectedDevice = [self.devices objectAtIndex:[[self.tableView indexPathForSelectedRow] row]];
JobDetailViewController *destViewController = segue.destinationViewController;
destViewController.device = selectedDevice;
}
}
and the code for the query:
#pragma Search Methods
-(void)filterContentForSearchText:(NSString *)searchText scope:(NSString *)scope
{
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"SELF beginswith[c] %#",searchText];
self.searchResults = [self.devices filteredArrayUsingPredicate:predicate];
}
-(BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString
{
[self filterContentForSearchText:searchString scope:[[self.searchDisplayController.searchBar scopeButtonTitles] objectAtIndex:[self.searchDisplayController.searchBar selectedScopeButtonIndex]]];
return YES;
}
but it keeps breaking when i enter the first letter. What can i do?
Not a predicate expert but shouldnt SELF beginswith[c] %# be text1 beginswith[c] %# since the predicate is used on an array of object Device
I've solved it. I've added this line of code.
if (!cell) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
// More initializations if needed.
}
just below
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
Thanks for all the help guys!

Terminating App due to'NSInvalidArgumentException'

I am trying to search my array contents from the TableView,The Cells Have Detail View also.When i run my app in stimulator it runs but when i insert objects dynamically and try to search them app crashes with 'NSInvalidArgumentException'.
reason:
'Can't use in/contains operator with collection <customcells: 0x8ea3b40> (not a collection)'.
My code which has Predicates is
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
self.searchedarray = nil;
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"SELF contains [cd] %#", self.searchtext.text];
self.searchedarray =[NSMutableArray arrayWithArray :[contactsarray filteredArrayUsingPredicate:predicate]];
}
and also
-(void)filterContentForSearchText:(NSString*)searchText scope:(NSString*)scope {
[searchedarray removeAllObjects];
// Filter the array using NSPredicate
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"self.name CONTAINS[c] %#", searchText];
searchedarray = [NSMutableArray arrayWithArray:[contactsarray filteredArrayUsingPredicate:predicate]];
}
Help me, I am stuck with this Predicate error ;Using Like instead of contains also doesn't help.
Edited content
- (void)viewDidLoad
{
contactsarray = [[NSMutableArray alloc] init];
self.searchedarray = [NSMutableArray arrayWithCapacity:[contactsarray count]];
[super viewDidLoad];
self.navigationItem.rightBarButtonItem = self.editButtonItem;
UIBarButtonItem *addButton = [[UIBarButtonItem alloc]
initWithBarButtonSystemItem:UIBarButtonSystemItemAdd
target:self
action:#selector(insertNewObject:)];
self.navigationItem.rightBarButtonItem = addButton;
}
- (void)insertNewObject:(id)sender
{
customcells *new = [[customcells alloc] init];
new.name = #"Enter Name";
new.contacts=#" Enter Contact Number";
new.organisation=#"Enter Organisation Name";
[contactsarray insertObject:new atIndex:0];
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
[self.tableView insertRowsAtIndexPaths:#[indexPath]
withRowAnimation:UITableViewRowAnimationAutomatic];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
// Return the number of sections.
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{// Return the number of rows in the section.
if (tableView == self.searchDisplayController.searchResultsTableView) {
return [searchedarray count];
} else {
return [contactsarray count];
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"cell";
UITableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:CellIdentifier];
customcells *myarray= [contactsarray objectAtIndex:indexPath.row];
cell.textLabel.text = myarray.name;
cell.textLabel.text = [NSString stringWithFormat:#"%#",
myarray.name];
if(cell==nil)
{
cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
if (tableView == self.searchDisplayController.searchResultsTableView)
{
customcells *newarray = [searchedarray objectAtIndex:indexPath.row];
cell.textLabel.text =newarray.name;
} else {
customcells *myarray= [contactsarray objectAtIndex:indexPath.row];
cell.textLabel.text = myarray.name;
cell.textLabel.text = [NSString stringWithFormat:#"%#",
myarray.name]; }
}
return cell;
}
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
// Return NO if you do not want the specified item to be editable.
return YES;
}
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
if (editingStyle == UITableViewCellEditingStyleDelete) {
// Delete the row from the data source
NSMutableArray *tempContent = [self.contactsarray mutableCopy];
[tempContent removeObject:[tempContent objectAtIndex:indexPath.row]];
self.contactsarray = tempContent;
[tableView deleteRowsAtIndexPaths:[NSMutableArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
} else if (editingStyle == UITableViewCellEditingStyleInsert) {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
self.searchedarray = nil;
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"SELF contains [cd] %#", self.searchtext.text];
self.searchedarray =[NSMutableArray arrayWithArray :[contactsarray filteredArrayUsingPredicate:predicate]];
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([[segue identifier] isEqualToString:#"showDetail"])
{
NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];
customcells *new = contactsarray[indexPath.row];
[[segue destinationViewController] setDetailItem:new];
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
}
-(void)filterContentForSearchText:(NSString*)searchText scope:(NSString*)scope {
[searchedarray removeAllObjects];
// Filter the array using NSPredicate
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"self.name CONTAINS[c] %#", searchText];
searchedarray = [NSMutableArray arrayWithArray:[contactsarray filteredArrayUsingPredicate:predicate]];
}
-(BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString {
// Tells the table data source to reload when text changes
[self filterContentForSearchText:searchString scope:
[[self.searchDisplayController.searchBar scopeButtonTitles] objectAtIndex:[self.searchDisplayController.searchBar selectedScopeButtonIndex]]];
// Return YES to cause the search result table view to be reloaded.
return YES;
}
-(BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchScope:(NSInteger)searchOption {
// Tells the table data source to reload when scope bar selection changes
[self filterContentForSearchText:self.searchDisplayController.searchBar.text scope:
[[self.searchDisplayController.searchBar scopeButtonTitles] objectAtIndex:searchOption]];
// Return YES to cause the search result table view to be reloaded.
return YES;
}
#end
Your code is using 'contains' in the NSPredicate, which assumes that each element in your array can be matched using 'contains'. You have an array of customcells, which will not by default have any way of dealing with a contains matcher.
In your second example, using self.name CONTAINS[c] %#, you end up matching on the name property which is a string, so I would expect this to work (though I've not tried it). The first example you give is trying to match on the customcells object directly, so I'd suggest also using self.name in that case as well.

iOS Search Address book contacts by UISearchBar using NSDictionary with multiple arrays

I am trying to implement search bar in my custom Contacts Book. I created NSDictionary for search data and added to my dictionary 4 mutable arrays, include
names, last name, phone types, phone numbers.
When I am trying to search in NSDictionary, my app is crashing on cell create. And When I am searching by one array only (from dictionary valueforkey or directly from array) it's working partially, but taking another strings (for example last name) always from the first contact in the list. Bacause not all parameters in a loop, So I have to search by every parameter to get right first name and last name in my contacts.
here is my code:
#pragma mark SEARCH_BAR
-(void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
[self.tableSearchBar resignFirstResponder];
}
-(void)searchBar:(UISearchBar *)serachBar textDidChange:(NSString *)searchText {
[filteredStrings removeAllObjects];
if (searchText.length == 0) {
isFiltered = NO;
} else {
isFiltered = YES;
//here aim creating NSDictionary with 4 Mutable Arrays
NSDictionary *filteredContacts = [NSDictionary dictionaryWithObjectsAndKeys:
contacts.firstNames, #"First Name",
contacts.lastNames, #"Last Name",
contacts.phoneTypes, #"Phone Type",
contacts.phoneNumbers, #"Phone Numbers",
nil];
//[filteredStrings addObject:filteredContacts];
for (NSString *str in filteredContacts) { // in this case for (NSString *str in [filteredContacts valueForKey:#"First Name"]) all working partially
NSRange stringRange = [str rangeOfString:searchText options:NSCaseInsensitiveSearch];
if (stringRange.location != NSNotFound) {
filteredStrings = [[NSMutableArray alloc]init];
[filteredStrings addObject:str];
}
}
}
[self.contactsTableView reloadData];
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if (isFiltered) {
return [filteredStrings count];
}
return [contacts.firstNames count];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellID = #"Cell";
abCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
if (!cell) {
cell = [tableView dequeueReusableCellWithIdentifier:cellID];
}
if (!isFiltered) {
cell.firstNameLabel.text = [contacts.firstNames objectAtIndex:indexPath.row];
cell.lastNameLabel.text = [contacts.lastNames objectAtIndex:indexPath.row];
cell.contactImage.image = [UIImage imageNamed:#"NOIMG.png"];
} else {
cell.firstNameLabel.text = [filteredStrings objectAtIndex:indexPath.row]; // Here my app is crashing when trying to search by all nsdictionary.
cell.lastNameLabel.text = [filteredStrings objectAtIndex:indexPath.row];
//cell.contactImage.image = [UIImage imageNamed:#"NOIMG.png"];
}
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
[self.contactsTableView deselectRowAtIndexPath:indexPath animated:YES];
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
if ([[segue identifier] isEqualToString:#"NextView"]) {
//if (!isFiltered) {
ContactDetailsViewController *nextController = [segue destinationViewController];
NSIndexPath *indexPath = [[[self contactsTableView] indexPathsForSelectedRows] objectAtIndex:0];
[nextController setPhoneTypes:[contacts.phoneTypes objectAtIndex:[indexPath row]]];
[nextController setPhoneNumbers:[contacts.phoneNumbers objectAtIndex:[indexPath row]]];
//}
/*else {
ContactDetailsViewController *nextController = [segue destinationViewController];
NSIndexPath *indexPath = [[[self contactsTableView] indexPathsForSelectedRows] objectAtIndex:0];
[nextController setPhoneTypes:[contacts.phoneTypes objectAtIndex:[indexPath row]]];
[nextController setPhoneNumbers:[contacts.phoneNumbers objectAtIndex:[indexPath row]]];
}*/
}
}

Resources