I have a UITableView which shows all of the songs in the Music Library, which works fine. However, when I start typing in the search bar to narrow down the search results, the app crashes immediately. Like as soon as I press one letter on the keyboard, it crashes. I've tried reworking my textDidChange: method but it always crashes, no matter what. I'm not sure what I'm doing wrong, could anyone help? Thanks.
Header:
#interface PTTableViewController : UIViewController <UITableViewDelegate, UITableViewDataSource, UISearchBarDelegate>
#property (strong,nonatomic)UITableView* tableView;
#property (strong,nonatomic)UISearchBar* searchBar;
#end
ViewController.m:
#import "PTTableViewController.h"
#implementation PTTableViewController
MPMediaQuery *songsQuery;
NSArray *songsArray;
NSMutableArray *filteredArray;
NSMutableArray *songTitlesArray;
-(void)viewDidLoad{
[super viewDidLoad];
self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0,0,[UIScreen mainScreen].bounds.size.width - 75,150) style:UITableViewStylePlain];
self.tableView.dataSource = self;
self.tableView.delegate = self;
[self.view addSubview:_tableView];
self.searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0,0,320,44)];
self.searchBar.delegate = self;
self.searchBar.placeholder = #"Search";
self.tableView.tableHeaderView = self.searchBar;
songsQuery = [MPMediaQuery songsQuery];
songsArray = [songsQuery items];
songTitlesArray = [[NSMutableArray alloc] init];
for (MPMediaItem *item in songsArray) {
[songTitlesArray addObject:[item valueForProperty:MPMediaItemPropertyTitle]];
}
filteredArray = [[NSMutableArray alloc] init];
filteredArray = [songTitlesArray copy];
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return filteredArray.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"cell"];
if (cell == nil){
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"cell"];
}
cell.textLabel.text = [filteredArray objectAtIndex:indexPath.row];
return cell;
}
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{
NSLog(#"search changed");
[self performSelectorInBackground:#selector(helper) withObject:nil];
}
-(void)helper{
[filteredArray removeAllObjects];
if ([self.searchBar.text isEqualToString:#""]){
filteredArray = [songTitlesArray copy];
} else {
for (NSString *object in songTitlesArray){
if ([object rangeOfString:self.searchBar.text].location == NSNotFound){
NSLog(#"string not found");
} else {
NSLog(#"string found");
[filteredArray addObject:object];
}
}
} [self.tableView reloadData];
}
#end
First...
You're getting a crash because you do this:
filteredArray = [songTitlesArray copy];
Which assigns a non-mutable copy of songTitlesArray to filteredArray.
When you then try to do this:
[filteredArray removeAllObjects];
you're trying to mutate a non-mutable object.
You can fix this (first) problem in a couple ways...
One way is to change all instances of copy to mutableCopy:
filteredArray = [songTitlesArray mutableCopy];
However, using your exact code, you'll introduce new crashes because you'll be executing UI actions on a background thread.
Next... Are you sure you're getting "keyboard lag"?
You may want to change a few things:
make _filteredArray non-mutable
instead of calling removeAllObjects simply re-create the array
use filteredArrayUsingPredicate instead of looping through and comparing each string
Give this a try - because I don't have your MPMediaQuery I'll generate 500 strings as "song titles":
#interface PTTableViewController : UIViewController <UITableViewDelegate, UITableViewDataSource, UISearchBarDelegate>
#property (strong,nonatomic)UITableView* tableView;
#property (strong,nonatomic)UISearchBar* searchBar;
#end
#implementation PTTableViewController
//MPMediaQuery *songsQuery;
NSArray *songsArray;
NSArray *filteredArray;
NSMutableArray *songTitlesArray;
-(void)viewDidLoad{
[super viewDidLoad];
self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0,0,[UIScreen mainScreen].bounds.size.width - 75,150) style:UITableViewStylePlain];
self.tableView.dataSource = self;
self.tableView.delegate = self;
[self.view addSubview:_tableView];
self.searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0,0,320,44)];
self.searchBar.delegate = self;
self.searchBar.placeholder = #"Search";
self.tableView.tableHeaderView = self.searchBar;
// songsQuery = [MPMediaQuery songsQuery];
// songsArray = [songsQuery items];
//
// songTitlesArray = [[NSMutableArray alloc] init];
// for (MPMediaItem *item in songsArray) {
// [songTitlesArray addObject:[item valueForProperty:MPMediaItemPropertyTitle]];
// }
// filteredArray = [[NSMutableArray alloc] init];
// filteredArray = [songTitlesArray copy];
// I don't have your Query, so let's create a 500 element string array,
// using the row number + one of the following words in each entry
NSString *samples = #"These are some random words for the song titles.";
// So, we'll have:
// "Row: 0 These"
// "Row: 1 are"
// "Row: 2 some"
// "Row: 3 random"
// "Row: 4 words"
// "Row: 5 for"
// "Row: 6 the"
// "Row: 7 song"
// "Row: 8 titles."
// "Row: 9 These"
// "Row: 10 are"
// "Row: 11 some"
// "Row: 12 random"
// "Row: 13 words"
// "Row: 14 for"
// ... etc
NSArray *a = [samples componentsSeparatedByString:#" "];
songTitlesArray = [[NSMutableArray alloc] init];
for (int i = 0; i < 500; i++) {
NSString *w = a[i % [a count]];
NSString *s = [NSString stringWithFormat:#"Row: %d %#", i, w];
[songTitlesArray addObject:s];
}
filteredArray = [songTitlesArray copy];
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return filteredArray.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"cell"];
if (cell == nil){
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"cell"];
}
cell.textLabel.text = [filteredArray objectAtIndex:indexPath.row];
return cell;
}
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{
[self helper];
}
-(void)helper{
if ([self.searchBar.text isEqualToString:#""]){
filteredArray = [songTitlesArray copy];
} else {
NSString *w = [NSString stringWithFormat:#"SELF contains[c] '%#'", self.searchBar.text];
NSPredicate *sPredicate = [NSPredicate predicateWithFormat:w];
filteredArray = [songTitlesArray filteredArrayUsingPredicate:sPredicate];
}
[self.tableView reloadData];
}
#end
As a side note, you've done a nice job of demonstrating one of the (many) reasons NOT to try and develop on a jailbroken device.
Related
I have one tableview and I created one UISearchController programmatically and added to tableview.
Initially it looks good but when I press on inside the search bar it looks below.
I don't want to keep my searchbar in navigation bar. And I can not use UITableViewController.
Find the code below which I implemented.
My .h file
#property (strong, nonatomic) UISearchController *searchController;
NSMutableArray *tableData;
NSArray *filteredContentList;
My .m file
// New SearchController.
self.searchController = [[UISearchController alloc] initWithSearchResultsController:nil];
self.searchController.searchResultsUpdater = self;
self.searchController.dimsBackgroundDuringPresentation = NO;
self.searchController.searchBar.delegate = self;
self.searchController.searchBar.searchBarStyle = UISearchBarStyleProminent;
[self.searchController.searchBar sizeToFit];
self.tblUserList.tableHeaderView = self.searchController.searchBar;
self.definesPresentationContext = YES;
#pragma mark - UISearchDisplayDelegate
- (void)updateSearchResultsForSearchController:(UISearchController *)searchController {
NSString *searchString = searchController.searchBar.text;
NSPredicate *resultPredicate;
//resultPredicate = [NSPredicate predicateWithFormat:#"displayname contains[c] %#",searchString];
resultPredicate = [NSPredicate predicateWithFormat:#"value contains[c] %#", searchString];
filteredContentList = [tableData filteredArrayUsingPredicate:resultPredicate];
//filteredContentList = [[tableData valueForKey:#"data"] filteredArrayUsingPredicate:resultPredicate];
[self.tblUserList reloadData];
}
- (void)searchBar:(UISearchBar *)searchBar selectedScopeButtonIndexDidChange:(NSInteger)selectedScope {
[self updateSearchResultsForSearchController:self.searchController];
}
- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
CGRect searchBarFrame = self.searchController.searchBar.frame;
[self.tblUserList scrollRectToVisible:searchBarFrame animated:NO];
return NSNotFound;
}
I want to show my searchbar above the tableview not in naviationbar.
Thanks in advance.
Late answer by myself.
I use UITextFiled instead of UISearchBar. Below is my code implementation.
[self.searchTextField addTarget:self action:#selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
And my textFieldDidChange method
-(void)textFieldDidChange:(UITextField *)textField
{
searchTextString=textField.text;
[self updateSearchArray:searchTextString];
}
-(void)updateSearchArray:(NSString *)searchText {
if(searchText.length==0) {
isFilter=NO;
} else {
isFilter=YES;
filteredContentList = [[NSMutableArray alloc]init];
NSPredicate *resultPredicate;
resultPredicate = [NSPredicate predicateWithFormat:#"value contains[c] %#", searchText];
filteredContentList = [tableData filteredArrayUsingPredicate:resultPredicate];
[self.tblUserList reloadData];
}
}
And my TableView methods:
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
NSInteger numOfSections = 0;
if ([filteredContentList count] || [tableData count]) {
_tblUserList.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
numOfSections = 1;
_tblUserList.backgroundView = nil;
} else {
UILabel *noDataLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, _tblUserList.bounds.size.width, _tblUserList.bounds.size.height)];
noDataLabel.text = NSLocalizedString(#"No Users found", #"Message");
noDataLabel.textColor = [UIColor blackColor];
noDataLabel.textAlignment = NSTextAlignmentCenter;
_tblUserList.backgroundView = noDataLabel;
_tblUserList.separatorStyle = UITableViewCellSeparatorStyleNone;
}
return numOfSections;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
/*if (isSearching) {
return [filteredContentList count];
}
else {
return [tableData count];
}*/
if (isFilter) {
return [filteredContentList count];
} else {
return [tableData count];
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *simpleTableIdentifier = #"SimpleTableItem";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier];
}
//cell.textLabel.text = [[tableData objectAtIndex:indexPath.row] valueForKeyPath:#"data.displayname"];
// Configure the cell...
if (isFilter) {
//cell.textLabel.text = [filteredContentList objectAtIndex:indexPath.row];
cell.textLabel.text = [[filteredContentList objectAtIndex:indexPath.row] valueForKeyPath:#"data.displayname"];
}
else {
cell.textLabel.text = [[tableData objectAtIndex:indexPath.row] valueForKeyPath:#"data.displayname"];
}
return cell;
}
I have added my delegate method and
I have a UITableView with a list of names. It has sections with an alphabetical index on the right hand side (see picture).
My program crashes whenever I enter a first character in the search field. I get the following error:
UpdateSearchResultsForSearchController
[__NSArrayM objectAtIndex:]: index 0 beyond bounds for empty array'
Understand I am trying to access an empty array, in the method UpdateSearchResultsForSearchController.
The program crashes in the last line of the method.
[((UITableViewController *)self.searchController.searchResultsController).tableView reloadData];
Here is the header
#import <UIKit/UIKit.h>
#import "EmployeeDatabase.h"
#interface EmployeeListViewController : UITableViewController<UISearchResultsUpdating, UISearchBarDelegate>
#property (nonatomic, strong) NSMutableArray *employees;
#property (nonatomic, strong) UISearchController *searchController;
#property (nonatomic, strong) NSMutableArray *tableSections;
#property (nonatomic, strong) NSMutableArray *tableSectionsAndItems;
#end
and here is the implementation
#import "EmployeeListViewController.h"
#import "EmployeeDetailViewController.h"
#implementation EmployeeListViewController
- (void)viewDidLoad {
[super viewDidLoad];
[self initializeTableContent];
[self initializeSearchController];
[self styleTableView];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
#pragma mark - Initialization methods
- (void)initializeTableContent {
self.employees = [EmployeeDatabase getEmployees];
self.tableSections = [NSMutableArray array];
self.tableSectionsAndItems = [NSMutableArray array];
for (employee *name in self.employees) {
NSString *key = [[name.lstNme substringToIndex: 1] uppercaseString];
if ([self.tableSections containsObject:key] == false) {
[self.tableSections addObject:key];
NSMutableArray *tmpArray = [NSMutableArray array];
[tmpArray addObject:name.fulNme];
NSMutableDictionary *tmpDictionary = [NSMutableDictionary dictionaryWithObject:tmpArray forKey:key];
[self.tableSectionsAndItems addObject:tmpDictionary];
} else {
NSMutableArray *tmpArray = [NSMutableArray array];
NSUInteger index = [self.tableSections indexOfObject:key];
NSMutableDictionary *tmpDictionary = [self.tableSectionsAndItems objectAtIndex:index];
tmpArray = [tmpDictionary objectForKey:key];
[tmpArray addObject:name.fulNme];
[self.tableSectionsAndItems removeObjectAtIndex:index];
[self.tableSectionsAndItems addObject:tmpDictionary];
}
}
}
- (void)initializeSearchController {
//instantiate a search results controller for presenting the search/filter results (will be presented on top of the parent table view)
UITableViewController *searchResultsController = [[UITableViewController alloc] initWithStyle:UITableViewStylePlain];
searchResultsController.tableView.dataSource = self;
searchResultsController.tableView.delegate = self;
//instantiate a UISearchController - passing in the search results controller table
self.searchController = [[UISearchController alloc] initWithSearchResultsController:searchResultsController];
//this view controller can be covered by theUISearchController's view (i.e. search/filter table)
self.definesPresentationContext = YES;
//define the frame for the UISearchController's search bar and tint
self.searchController.searchBar.frame = CGRectMake(self.searchController.searchBar.frame.origin.x,
self.searchController.searchBar.frame.origin.y,
self.searchController.searchBar.frame.size.width, 44.0);
self.searchController.searchBar.tintColor = [UIColor whiteColor];
//add the UISearchController's search bar to the header of this table
self.tableView.tableHeaderView = self.searchController.searchBar;
//this ViewController will be responsible for implementing UISearchResultsDialog protocol method(s) - so handling what happens when user types into the search bar
self.searchController.searchResultsUpdater = self;
//this ViewController will be responsisble for implementing UISearchBarDelegate protocol methods(s)
self.searchController.searchBar.delegate = self;
}
- (void)styleTableView {
[[self tableView] setSectionIndexColor:[UIColor colorWithRed:100.0f/255.0f green:100.0f/255.0f blue:100.0f/255.0f alpha:1.0f]];
[[self tableView] setSectionIndexBackgroundColor:[UIColor colorWithRed:230.0f/255.0f green:230.0f/255.0f blue:230.0f/255.0f alpha:1.0f]];
}
#pragma mark - UITableViewDataSource methods
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return [self.tableSections count];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
NSDictionary *sectionItems = [self.tableSectionsAndItems objectAtIndex:section];
NSArray *namesForSection = [sectionItems objectForKey:[self.tableSections objectAtIndex:section]];
return [namesForSection count];
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
return [self.tableSections objectAtIndex:section];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellReuseId = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellReuseId];
if(cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellReuseId];
}
NSDictionary *sectionItems = [self.tableSectionsAndItems objectAtIndex:indexPath.section];
NSArray *namesForSection = [sectionItems objectForKey:[self.tableSections objectAtIndex:indexPath.section]];
cell.textLabel.text = [namesForSection objectAtIndex:indexPath.row];
//show accessory disclosure indicators on cells only when user has typed into the search box
if(self.searchController.searchBar.text.length > 0) {
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
}
return cell;
}
#pragma mark - UITableViewDelegate methods
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
NSDictionary *sectionItems = [self.tableSectionsAndItems objectAtIndex:indexPath.section];
NSArray *namesForSection = [sectionItems objectForKey:[self.tableSections objectAtIndex:indexPath.section]];
NSString *selectedItem = [namesForSection objectAtIndex:indexPath.row];
//Log
NSLog(#"User selected %#", selectedItem);
}
//#pragma Segue
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
if ([[segue identifier] isEqualToString:#"showDetail"]) {
NSIndexPath *indexPath = [self.tableView indexPathForCell:sender];
employee *employee = self.employees[indexPath.row];
EmployeeDetailViewController *employeeDetailViewController = segue.destinationViewController;
employeeDetailViewController.detailItem = employee;
}
}
- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView {
//only show section index titles if there is no text in the search bar
if(!(self.searchController.searchBar.text.length > 0)) {
NSArray *indexTitles = self.tableSections;
//HERE
//*indexTitles = [Item fetchDistinctItemGroupsInManagedObjectContext:self.managedObjectContext];
return indexTitles;
} else {
return nil;
}
}
- (void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section
{
view.tintColor = [UIColor colorWithRed:100.0f/255.0f green:100.0f/255.0f blue:100.0f/255.0f alpha:1.0f];
UITableViewHeaderFooterView *header = (UITableViewHeaderFooterView *)view;
[header.textLabel setTextColor:[UIColor whiteColor]];
}
#pragma mark - UISearchResultsUpdating
-(void)updateSearchResultsForSearchController:(UISearchController *)searchController {
//get search text from user input
NSString *searchText = [self.searchController.searchBar text];
//exit if there is no search text (i.e. user tapped on the search bar and did not enter text yet)
if(!([searchText length] > 0)) {
return;
}
//handle when there is search text entered by the user
else {
//based on the user's search, we will update the contents of the tableSections and tableSectionsAndItems properties
[self.tableSections removeAllObjects];
[self.tableSectionsAndItems removeAllObjects];
NSString *firstSearchCharacter = [searchText substringToIndex:1];
//handle when user taps into search bear and there is no text entered yet
if([searchText length] == 0) {
//self.tableSections = [[Item fetchDistinctItemGroupsInManagedObjectContext:self.managedObjectContext] mutableCopy];
//self.tableSectionsAndItems = [[Item fetchItemNamesByGroupInManagedObjectContext:self.managedObjectContext] mutableCopy];
}
//handle when user types in one or more characters in the search bar
else if(searchText.length > 0) {
//the table section will always be based off of the first letter of the group
NSString *upperCaseFirstSearchCharacter = [firstSearchCharacter uppercaseString];
self.tableSections = [[[NSArray alloc] initWithObjects:upperCaseFirstSearchCharacter, nil] mutableCopy];
//there will only be one section (based on the first letter of the search text) - but the property requires an array for cases when there are multiple sections
//NSDictionary *namesByGroup = [Item fetchItemNamesByGroupFilteredBySearchText:searchText ////inManagedObjectContext:self.managedObjectContext];
//self.tableSectionsAndItems = [[[NSArray alloc] initWithObjects:namesByGroup, nil] mutableCopy];
}
//now that the tableSections and tableSectionsAndItems properties are updated, reload the UISearchController's tableview
[((UITableViewController *)self.searchController.searchResultsController).tableView reloadData];
}
}
#pragma mark - UISearchBarDelegate methods
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar {
[self.tableSections removeAllObjects];
[self.tableSectionsAndItems removeAllObjects];
//self.tableSections = [[Item fetchDistinctItemGroupsInManagedObjectContext:self.managedObjectContext] mutableCopy];
//self.tableSectionsAndItems = [[Item fetchItemNamesByGroupInManagedObjectContext:self.managedObjectContext] mutableCopy];
}
#end
The problem is that, your are removing all objects at this line
[self.tableSectionsAndItems removeAllObjects];
and you have commented the lines, which again feels that array, just above the lines which you mentioned in your question. so, uncomment the following lines
//NSDictionary *namesByGroup = [Item fetchItemNamesByGroupFilteredBySearchText:searchText ////inManagedObjectContext:self.managedObjectContext];
//self.tableSectionsAndItems = [[[NSArray alloc] initWithObjects:namesByGroup, nil] mutableCopy];
And in numberOfRows Method, you are accessing the object at index on empty array that leads to crash.
[self.tableSectionsAndItems objectAtIndex:section];
So, uncomment those two lines above, in the following method and it will fix.
-(void)updateSearchResultsForSearchController:(UISearchController *)searchController
Try and share your results.
I have a UITableView with search bar function. However, when i search for any keyword (Please refer to screenshot as attached), search result will be repeated and return more than 1 result.
My expected result should be search result will reflect accordingly based on keyword entered.
Your help is much appreciated. Please help, thank you.
#interface Friend_ViewController ()
#end
#implementation Friend_ViewController{
NSMutableArray *tableData;
UITableView *tableView;
BOOL isFiltered;
NSMutableArray *stateNamesArray;
NSArray *searchResult;
}
- (void)viewDidLoad {
[super viewDidLoad];
isFiltered =false;
UIImage* image3 = [UIImage imageNamed:#"Add_Friend"];
CGRect frameimg = CGRectMake(0,0, image3.size.width -10, image3.size.height);
UIButton *btn_add_friends = [[UIButton alloc] initWithFrame:frameimg];
[btn_add_friends setBackgroundImage:image3 forState:UIControlStateNormal];
[btn_add_friends addTarget:self action:#selector(addFriendButtonDidPressed:)
forControlEvents:UIControlEventTouchUpInside];
[btn_add_friends setShowsTouchWhenHighlighted:YES];
UIBarButtonItem *btn_add_friends_item =[[UIBarButtonItem alloc] initWithCustomView:btn_add_friends];
self.navigationItem.rightBarButtonItem =btn_add_friends_item;
stateNamesArray = #[#"Alabama", #"Alaska", #"Arizona", #"Arkansas", #"California", #"Colorado", #"Connecticut", #"Delaware", #"Florida", #"Georgia", #"Hawaii", #"Idaho", #"Illinois", #"Indiana", #"Iowa", #"Kansas", #"Kentucky", #"Louisiana", #"Maine", #"Maryland", #"Massachusetts", #"Michigan",
#"Minnesota", #"Mississippi", #"Missouri", #"Montana", #"Nebraska", #"Nevada", #"New Hampshire",
#"New Jersey", #"New Mexico", #"New York", #"North Carolina", #"North Dakota", #"Ohio",
#"Oklahoma", #"Oregon", #"Pennsylvania", #"Rhode Island", #"South Carolina", #"South Dakota",
#"Tennessee", #"Texas", #"Utah", #"Vermont", #"Virginia", #"Washington", #"West Virginia",
#"Wisconsin", #"Wyoming"];
NSInteger indexLabelLettersCount = [[UILocalizedIndexedCollation currentCollation] sectionTitles].count;
NSMutableArray *allSections = [[NSMutableArray alloc] initWithCapacity:indexLabelLettersCount];
for (int i = 0; i < indexLabelLettersCount; i++) {
[allSections addObject:[NSMutableArray array]];
}
for(NSString *theState in stateNamesArray){
NSInteger sectionNumber = [[UILocalizedIndexedCollation currentCollation] sectionForObject:theState collationStringSelector:#selector(lowercaseString)];
[allSections[sectionNumber] addObject:theState];
}
NSMutableArray *sortedArray = [[NSMutableArray alloc] init];
self.activeSectionIndices = [NSMutableDictionary dictionary];
self.activeSectionTitles = [NSMutableArray array];
for (int i = 0; i < indexLabelLettersCount; i++) {
NSArray *statesForSection = allSections[i];
NSString *indexTitleForSection = [[UILocalizedIndexedCollation currentCollation] sectionTitles][i];
if (statesForSection.count > 0) {
[self.activeSectionTitles addObject:indexTitleForSection];
NSArray *tmpSectionStates = allSections[i];
tmpSectionStates = [tmpSectionStates sortedArrayUsingSelector:#selector(compare:)];
[sortedArray addObject:tmpSectionStates];
}
NSNumber *index = [NSNumber numberWithInt:MAX(self.activeSectionTitles.count - 1, 0)];
self.activeSectionIndices[indexTitleForSection] = index;
}
tableData = sortedArray;
self.tableView.sectionHeaderHeight = 25;
self.navigationController.navigationBar.translucent = NO;
tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
self.navigationController.navigationBar.translucent = NO;
self.tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
self.searchController = [[UISearchController alloc] initWithSearchResultsController:nil];
self.tableView.tableHeaderView = self.searchController.searchBar;
self.searchController.searchResultsUpdater = self;
self.searchController.dimsBackgroundDuringPresentation = NO;
self.searchController.hidesNavigationBarDuringPresentation = NO;
self.searchController.searchBar.delegate = self;
self.definesPresentationContext = YES;
[self.searchController.searchBar sizeToFit];
[self.view addSubview:self.searchBar];
searchResult = [NSMutableArray arrayWithCapacity:[stateNamesArray count]];
}
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(nonnull NSString *)searchText
{
if(searchText.length == 0)
{
isFiltered = NO;
}
else
{
isFiltered = YES;
NSPredicate *resultPredicate = [NSPredicate
predicateWithFormat:#"SELF CONTAINS %#",
searchText];
searchResult = [stateNamesArray filteredArrayUsingPredicate:resultPredicate];
}
[self.tableView reloadData];
}
- (NSInteger)numberOfSectionsInTableView: (UITableView *) tableView{
return tableData.count;
}
- (NSInteger)tableView: (UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
if(isFiltered){
return searchResult.count;
}
else
{
NSArray *arr = tableData[section];
return arr.count;
}
}
- (UITableViewCell *) tableView:(UITableView *) tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"cell"];
if(cell == nil){
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"cell"];
}
if(isFiltered){
cell.textLabel.text = [searchResult objectAtIndex:indexPath.row];
cell.imageView.image = [UIImage imageNamed:#"Home"];
}
else{
NSArray *arr = tableData[indexPath.section];//get the current section array
cell.textLabel.text = arr[indexPath.row];//get the row for the current section
cell.imageView.image = [UIImage imageNamed:#"Home"];
}
return cell;
}
-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
if(isFiltered)
{
return nil;
}
return self.activeSectionTitles[section];
}
#end
</pre></code>
You are always returning tableData.count in numberOfSectionsInTableView so every row is repeated tableData.count times.
- (NSInteger)numberOfSectionsInTableView: (UITableView *) tableView{
return isFiltered ? 1 : tableData.count;
}
- (NSInteger)tableView: (UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
NSArray sectionArray = (NSArray *)tableData[section];
return isFiltered ? 1 : sectionArray.count;
}
You are always returning tableData.count in numberOfSectionsInTableView so
You need to return proper section count.
- (NSInteger)numberOfSectionsInTableView: (UITableView *) tableView{
return isFiltered ? 1 : tableData.count;
}
I hope this will help you. :)
update this code
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(nonnull NSString *)searchText
{
//Add below line of code
[searchText removeAllObjects];
if(searchText.length == 0)
{
isFiltered = NO;
}
else
{
isFiltered = YES;
NSPredicate *resultPredicate = [NSPredicate
predicateWithFormat:#"SELF CONTAINS %#",
searchText];
searchResult = [stateNamesArray filteredArrayUsingPredicate:resultPredicate];
}
[self.tableView reloadData];
}
This method calls on every character, so it search and result store in array. You are not removing object from array so it keep adding object in it. That's why you are getting this result.
[searchText removeAllObjects];
This line of code remove all objects from array.
I've created an UITableView with cells and i am trying to add a person's phone and name information into a cell via some functions. The problem is when i try to add a person's info, it is being added into my data array but, i cannot see the new info on UITableView cell. I tried to use reloadData function to reload UITableView, it was no use.
I have arrays for people's numbers and names. Also, i have a button which adds a person via ABPeoplePickerNavigationController.
addedContacts.h :
#import <UIKit/UIKit.h>
#import AddressBook;
#import AddressBookUI;
#interface addedContacts : UIViewController <UITextFieldDelegate, ABPeoplePickerNavigationControllerDelegate, UITableViewDelegate,
UITableViewDataSource>{
NSMutableArray* people;
NSMutableArray* numbers;
IBOutlet UITableView *tableview;
}
- (IBAction)addPerson:(id)sender;
#end
I use commitEditingStyle function to delete a person's information from the tableview. In addition, I keep people's information in defaults of application.
addedContacts.m :
#import "addedContacts.h"
#implementation addedContacts
-(void)viewDidLoad{
[super viewDidLoad];
}
- (IBAction)addPerson:(id)sender {
ABPeoplePickerNavigationController* picker = [[ABPeoplePickerNavigationController alloc] init];
picker.peoplePickerDelegate = self;
[self presentViewController:picker animated:YES completion:nil];
}
- (void)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker didSelectPerson:(ABRecordRef)person property:(ABPropertyID)property identifier:(ABMultiValueIdentifier)identifier {
[self dismissViewControllerAnimated:YES completion:nil];
}
-(BOOL)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker shouldContinueAfterSelectingPerson:(ABRecordRef)person{
NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
numbers = [[NSMutableArray alloc] initWithArray:[defaults objectForKey:#"numbers"]];
people = [[NSMutableArray alloc] initWithArray:[defaults objectForKey:#"people"]];
if(numbers.count == 0 && numbers.count == 0){
numbers = [[NSMutableArray alloc] init];
people = [[NSMutableArray alloc] init];
}
NSString *contactName = CFBridgingRelease(ABRecordCopyCompositeName(person));
NSString* nameField = [NSString stringWithFormat:#"%#", contactName ? contactName : #"No Name"];
ABMultiValueRef phoneRecord = ABRecordCopyValue(person, kABPersonPhoneProperty);
CFStringRef phoneNumber = ABMultiValueCopyValueAtIndex(phoneRecord, 0);
NSString* phoneField = (__bridge_transfer NSString *)phoneNumber;
CFRelease(phoneRecord);
[people addObject:nameField];
[numbers addObject:phoneField];
[defaults setObject:people forKey:#"people"];;
[defaults setObject:numbers forKey:#"numbers"];
[self dismissViewControllerAnimated:YES completion:nil];
return NO;
}
-(void)peoplePickerNavigationControllerDidCancel:(ABPeoplePickerNavigationController *)peoplePicker{
[self dismissViewControllerAnimated:YES completion:nil];
}
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
// Remove the row from data model
[people removeObjectAtIndex:indexPath.row];
[numbers removeObjectAtIndex:indexPath.row];
// Request table view to reload
[tableView reloadData];
}
-(NSInteger) numberOfSectionsInTableView: (UITableView*) tableView{
return 1;
}
-(NSInteger) tableView:(UITableView*) tableView numberOfRowsInSection:(NSInteger)section{
NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
numbers = [[NSMutableArray alloc] initWithArray:[defaults objectForKey:#"numbers"]];
return [numbers count];
}
-(UITableViewCell*) tableView: (UITableView*)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
numbers = [[NSMutableArray alloc] initWithArray:[defaults objectForKey:#"numbers"]];
people = [[NSMutableArray alloc] initWithArray:[defaults objectForKey:#"people"]];
NSLog(#"%#",numbers);
NSLog(#"%#",people);
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"cell"];
if(cell == nil){
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"cell"];
cell.accessoryType = UITableViewCellAccessoryDetailButton;
}
NSLog(#"%ld", (long)indexPath.row);
NSLog(#"%ld", (long)people.count);
NSString* Tname = [people objectAtIndex:indexPath.row];
NSString* Tnumber = [numbers objectAtIndex:indexPath.row];
cell.textLabel.text = Tname;
cell.detailTextLabel.text = Tnumber;
return cell;
}
#end
Any suggestions?
1) this is something strange:
if(numbers.count == 0 && numbers.count == 0){
numbers = [[NSMutableArray alloc] init];
people = [[NSMutableArray alloc] init];
}
i think you mean
if(numbers.count == 0 && people.count == 0)
2) i think you mast insert reload of table after you add your new object into people and numbers arrays
[people addObject:nameField];
[numbers addObject:phoneField];
[tableView reloadData];
My hunch is that, there this a bug in the tableView:numberOfRowsInSection code. You need to return count of people or numbers. Not get the value from the user defaults. Since they don't have the newly added person and number.
-(NSInteger) tableView:(UITableView*) tableView numberOfRowsInSection:(NSInteger)section{
return [numbers count];
}
I'm trying to implement a UISearchBar in a custom UITableViewController and done programmatically (not using IB). I got the search function to work and return the correct fields, but it is displaying the searched cells over the full list cells:
As you can see, the new searched field is scrollable and selectable. Its just not removing the old cells.
here is my .h file:
#interface TestTableViewController : UITableViewController <UISearchBarDelegate, UISearchDisplayDelegate>
#property (strong, nonatomic) NSArray *boundaries;
#end
.m file:
#import "TestTableViewController.h"
#import "Boundary.h"
#interface TestTableViewController ()
#property (strong, nonatomic) UISearchDisplayController *searchController;
#property (strong, nonatomic) NSMutableArray *filteredBoundaries;
#end
#implementation TestTableViewController
-(instancetype) initWithStyle:(UITableViewStyle)style {
self = [super initWithStyle:style];
if (self) {
self.filteredBoundaries = [NSMutableArray array];
}
return self;
}
-(void)viewDidLoad {
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:#"name" ascending:TRUE selector:#selector(caseInsensitiveCompare:)];
NSArray *sortDescriptors = #[sortDescriptor];
self.boundaries = [self.boundaries sortedArrayUsingDescriptors:sortDescriptors];
UISearchBar *searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, 320, 44)];
searchBar.delegate = self;
searchBar.placeholder = #"Search Fields";
searchBar.showsCancelButton = TRUE;
self.tableView.tableHeaderView = searchBar;
self.searchController = [[UISearchDisplayController alloc] initWithSearchBar:searchBar contentsController:self];
self.searchController.delegate = self;
self.searchController.searchResultsDataSource = self;
self.searchController.searchResultsDelegate = self;
}
// ------------------------------------------------------------------------------------------------------
#pragma mark -
#pragma mark Setup Filter Data Source
-(void)filterContentForSearchText:(NSString *)searchText scope:(NSString *)scope {
[self.filteredBoundaries removeAllObjects];
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"name contains[c] %#", searchText];
self.filteredBoundaries = [NSMutableArray arrayWithArray:[self.boundaries filteredArrayUsingPredicate:predicate]];
}
// ------------------------------------------------------------------------------------------------------
#pragma mark -
#pragma mark Table view data source
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
if (tableView == self.searchDisplayController.searchResultsTableView) {
return self.filteredBoundaries.count;
}
else {
return self.boundaries.count;
}
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
if (tableView == self.searchDisplayController.searchResultsTableView) {
Boundary *boundary = [self.filteredBoundaries objectAtIndex:indexPath.row];
cell.textLabel.text = boundary.name;
cell.textLabel.textColor = [UIColor blackColor];
cell.selectionStyle = UITableViewCellSelectionStyleBlue;
}
else {
Boundary *boundary = [self.boundaries objectAtIndex:indexPath.row];
cell.textLabel.text = boundary.name;
cell.textLabel.textColor = [UIColor blackColor];
cell.selectionStyle = UITableViewCellSelectionStyleBlue;
cell.userInteractionEnabled = TRUE;
}
return cell;
}
// ------------------------------------------------------------------------------------------------------
#pragma mark -
#pragma mark UISearchDisplayController Delegates
-(BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString {
[self filterContentForSearchText:searchString scope:[[self.searchController.searchBar scopeButtonTitles] objectAtIndex:self.searchController.searchBar.selectedScopeButtonIndex]];
return TRUE;
}
#end
And how I call the table view:
TestTableViewController *tableViewController = [[TestTableViewController alloc] initWithStyle:UITableViewStylePlain];
tableViewController.boundaries = [group.boundaries allObjects];
tableViewController.contentSizeForViewInPopover = POPOVER_SIZE;
UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:tableViewController];
navController.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
navController.navigationBar.barStyle = UIBarStyleBlack;
self.myPopoverController = [[UIPopoverController alloc] initWithContentViewController:navController];
self.myPopoverController.delegate = self;
[self.myPopoverController presentPopoverFromRect:button.frame inView:button.superview permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
Any ideas what I might be doing wrong or missing?
The problem is that UISearchDisplayController is using another UITableView rather than the view controller's own. You can verify that by logging tableView in -tableView:cellForRowAtIndexPath:.
You can use a UISearchBar without a UISearchDisplayController, to have more control over search and display logic.
Also, if your app doesn't support any version prior to iOS 8, consider using UISearchController. I haven't tried it but it seems to give you more control. Check a sample UISearchDisplayControllerhas been deprecated in iOS 8.
Try this
searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0.0, 0.0, 320.0, 41.0)];
[self.view addSubview:searchBar];
searchBar.delegate=self;
- (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 (isSearching) {
return [filteredContentList count];
}
else {
return [titlearray count];
}
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
// Return YES for supported orientations
return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *simpleTableIdentifier = #"SimpleTableCell";
SimpleTableCell *cell = (SimpleTableCell *)[tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
if (cell == nil)
{
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"SimpleTableCell" owner:self options:nil];
cell = [nib objectAtIndex:0];
}
if (isSearching)
{
cell.nameLabel.text = [filteredContentList objectAtIndex:indexPath.row];
cell.thumbnailImageView.image =[filteredImgArray objectAtIndex:indexPath.row];
}
else
{
cell.thumbnailImageView.image = [imagearray objectAtIndex:indexPath.row];
cell.nameLabel.text = [titlearray objectAtIndex:indexPath.row];
}
return cell;
}
- (void)searchTableList {
NSString *searchString = searchBar.text;
for (int i=0; i<titlearray.count; i++) {
NSString *tempStr=[titlearray objectAtIndex:i];
NSComparisonResult result = [tempStr compare:searchString options:(NSCaseInsensitiveSearch|NSDiacriticInsensitiveSearch) range:NSMakeRange(0, [searchString length])];
if (result == NSOrderedSame)
{
[filteredContentList addObject:tempStr];
[filteredImgArray addObject:[imagearray objectAtIndex:i]];
}
}
}
#pragma mark - Search Implementation
- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
isSearching = YES;
}
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
NSLog(#"Text change - %d",isSearching);
//Remove all objects first.
[filteredContentList removeAllObjects];
[filteredImgArray removeAllObjects];
if([searchText length] != 0) {
isSearching = YES;
[self searchTableList];
//tblContentList.hidden=NO;
}
else {
isSearching = NO;
// tblContentList.hidden=YES;
}
[tblContentList reloadData];
}
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar {
NSLog(#"Cancel clicked");
}
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
NSLog(#"Search Clicked");
[self searchTableList];
}
I hope it's help for you
You should implement correct datasource.
Create new array of items for filtered data for first.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
NSInteger count = ([filteredItems count] > 0) ? [filteredItems count] : [self.allItems count];
return count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
MyCustomCell *cell = [tableView dequeueReusableCellWithIdentifier: #"id"];
MyCustomItem *item = ([filteredItems count] > 0) ? filteredItems[indexPath.row] : self.allItems[indexPath.row];
[self configureCell:cell forItem:item];
return cell;
}
Configure searching:
- (void)updateSearchResultsForSearchController:(UISearchController *)searchController
{
NSString *searchText = searchController.searchBar.text;
if ([searchText length] == 0)
{
[filteredItems removeAllObjects];
[self.tableView reloadData];
return;
}
NSMutableArray *searchResults = [self.allItems mutableCopy];
// SKIP ALL BODY OF SEARCHING
filteredPeoples = searchResults;
[self.tableView reloadData];
}
Will work pretty.
IOS 8 delegate has been deprecated not sure if that's the problem.
The method
here's [a link]https://developer.apple.com/Library/ios/documentation/UIKit/Reference/UISearchDisplayDelegate_Protocol/index.html#//apple_ref/occ/intfm/UISearchDisplayDelegate/searchDisplayControS 8 delegate has been deprecated not sure if that's the problem.
The method
try this property instead
#property(nonatomic, assign) id< UISearchResultsUpdating > searchResultsUpdater
another better link [a link]https://developer.apple.com/library/ios/samplecode/TableSearch_UISearchController/Listings/TableSearch_obj_c_TableSearch_APLResultsTableController_m.html