I am new to iOS. I am making an app in which i am getting data from Parse back-end all are working fine.
I did UISearchbar and it works well. But when a search produces more than 6 results (main table have 6 rows, but I search for another Parse class) , this leads to an error.
2015-06-09 14:10:23.318 Aero store[3238:347073] Terminating app due to uncaught exception 'NSRangeException', reason: '
-[__NSArrayM objectAtIndex:]: index 6 beyond bounds [0 .. 5]'
This is my code:
#import "CategoryTable.h"
#import "GoodsTable.h"
#import "Parse/Parse.h"
#interface CategoryTable ()<UISearchDisplayDelegate, UISearchBarDelegate>
#property (nonatomic, strong) UISearchDisplayController *searchController;
#property (nonatomic, strong) NSMutableArray *searchResults;
#end
#implementation CategoryTable
#synthesize categoryId;
- (void)viewDidLoad {
[super viewDidLoad];
self.searchController = [[UISearchDisplayController alloc] initWithSearchBar:self.goodsSearchBar contentsController:self];
self.searchController.searchResultsDataSource = self;
self.searchController.searchResultsDelegate = self;
self.searchController.delegate = self;
[self.searchDisplayController.searchBar setBackgroundImage:[UIImage imageNamed:#"menu-background"]
forBarPosition:0
barMetrics:UIBarMetricsDefault];
CGPoint offset = CGPointMake(0, self.goodsSearchBar.frame.size.height);
self.tableView.contentOffset = offset;
self.searchResults = [NSMutableArray array];
self.navigationController.navigationBar.barStyle = UIStatusBarStyleLightContent;
self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:#" " style:UIBarButtonItemStylePlain target:nil action:nil];
if ([[NSUserDefaults standardUserDefaults] objectForKey:#"cityName"] != nil) {
//Город установлен - > категории
NSLog(#"Gorod - %#", [[NSUserDefaults standardUserDefaults] objectForKey:#"cityName"]);
//[self performSegueWithIdentifier:#"showCategory" sender:self];
}
else
{
//Город не установлен -> выбор города
NSLog(#"Gorod - %#", [[NSUserDefaults standardUserDefaults] objectForKey:#"cityName"]);
}
//Установка лого
UIView *headerView = [[UIView alloc] init];
headerView.frame = CGRectMake(0, 0, 151, 20);
UIImageView *logoImage = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"logo"]];
logoImage.frame = CGRectMake(0, 0, 151, 20);
logoImage.contentMode = UIViewContentModeScaleAspectFit;
[headerView addSubview:logoImage];
[self.navigationItem setTitleView:headerView];
}
- (id)initWithCoder:(NSCoder *)aDecoder
{
self = [super initWithCoder:aDecoder];
if (self) {
self.parseClassName = #"Category";
self.pullToRefreshEnabled = NO;
self.paginationEnabled = NO;
}
return self;
}
//Слово для поиска
-(BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString {
searchString = [searchString lowercaseString];
[self filterResults:searchString];
return NO;
}
//Запрос для поиска
-(void)filterResults:(NSString *)searchTerm {
if (searchTerm.length > 1) {
[PFCloud callFunctionInBackground:#"find"
withParameters:#{#"goodsName": searchTerm, #"city":[[NSUserDefaults standardUserDefaults] objectForKey:#"cityName"]}
block:^(NSArray *goodsList, NSError *error) {
if (!error) {
NSLog(#"Найдено: %#",goodsList);
[self.searchResults removeAllObjects];
[self.searchResults addObjectsFromArray:goodsList];
dispatch_async(dispatch_get_main_queue(), ^{
[self.searchController.searchResultsTableView reloadData];
});
}
}];
}
}
//Получени списка категорий
- (PFQuery *)queryForTable {
PFQuery *query = [PFQuery queryWithClassName:self.parseClassName];
[query whereKey:#"cityName" equalTo:[[NSUserDefaults standardUserDefaults] objectForKey:#"cityName"]];
if (self.objects.count == 0) {
query.cachePolicy = kPFCachePolicyCacheThenNetwork;
}
[query orderByAscending:#"createdAt"];
return query;
}
//Количество ячеек для результата поиска
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
if (tableView == self.searchDisplayController.searchResultsTableView) {
return self.searchResults.count;
}
else {
return self.objects.count;
}
}
//Обрезка пустых ячеек
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
UIView *sectionFooterView = [[UIView alloc] initWithFrame:
CGRectMake(0, 0, tableView.frame.size.width, 1)];
sectionFooterView.backgroundColor = [UIColor clearColor];
return sectionFooterView;
}
//Отрисовка ячеек категорий
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath object:(PFObject *)object {
static NSString *identifier = #"categoryCell";
PFTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
if (!cell) {
cell = [[PFTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
}
if (tableView == self.tableView) {
UILabel *titleLabel = (UILabel*) [cell viewWithTag:200];
titleLabel.text = [object objectForKey:#"title"];
PFFile *thumbnail = [object objectForKey:#"image"];
PFImageView *catImageView = (PFImageView*)[cell viewWithTag:100];
catImageView.image = [UIImage imageNamed:#"placeholder"];
catImageView.file = thumbnail;
[catImageView loadInBackground];
}
else if(tableView == self.searchDisplayController.searchResultsTableView) {
NSLog(#"test");
PFObject *searchedUser = [self.searchResults objectAtIndex:indexPath.row];
cell.textLabel.text = [[searchedUser objectForKey:#"name"] capitalizedString];
}
return cell;
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
if ([segue.identifier isEqualToString:#"showGoods"]) {
NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];
GoodsTable *goods= segue.destinationViewController;
PFObject *object = [self.objects objectAtIndex:indexPath.row];
categoryId = [object objectForKey:#"title"];
NSLog(#"Category Name = %#", categoryId);
goods.cityName = [[NSUserDefaults standardUserDefaults] objectForKey:#"cityName"];
goods.categoryId = categoryId;
}
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
#end
Please help me! I can not solve the problem for several days. :'(
Try
dispatch_async(dispatch_get_main_queue(), ^{
[self.searchResults removeAllObjects];
[self.searchResults addObjectsFromArray:goodsList];
[self.searchController.searchResultsTableView reloadData];
});
to ensure editing your datasource and reloading your tablew view are done in the same dispatch queue.
Related
I'm using Parse to populate a table view which works fine. I'm trying to delete a row from the table view but get this error:
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSArrayI length]: unrecognized selector sent to instance 0x7fd3f0f20f60'
Here is the code:
#import "CompletedJobs.h"
#import <Parse/Parse.h>
#interface CompletedJobs ()
#property (nonatomic, strong) NSMutableArray *jobs;
#property (nonatomic, strong) NSMutableArray *objectIds;
#property (nonatomic, strong) UIActivityIndicatorView *loadingIndicator;
#property (nonatomic, strong) UIRefreshControl *refresh;
#end
#implementation CompletedJobs
- (void)viewDidLoad {
[super viewDidLoad];
[self.tableView setDataSource:self];
[self.tableView setDelegate:self];
self.navigationItem.rightBarButtonItem = self.editButtonItem;
CGFloat width = CGRectGetWidth(self.view.bounds);
CGFloat height = CGRectGetHeight(self.view.bounds);
self.loadingIndicator = [[UIActivityIndicatorView alloc]initWithFrame:CGRectMake(width / 2, height / 2, 37, 37)];
self.loadingIndicator.center = CGPointMake(width / 2, height / 2 - 37);
self.loadingIndicator.autoresizingMask = (UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleTopMargin);
self.loadingIndicator.activityIndicatorViewStyle = UIActivityIndicatorViewStyleGray;
self.loadingIndicator.hidesWhenStopped = YES;
[self.view addSubview:self.loadingIndicator];
[self.loadingIndicator startAnimating];
[self getJobs];
self.refresh = [[UIRefreshControl alloc]init];
self.refresh.tintColor = [UIColor blackColor];
[self.refresh addTarget:self action:#selector(refreshData) forControlEvents:UIControlEventValueChanged];
self.refreshControl = self.refresh;
}
- (void)viewDidAppear:(BOOL)animated {
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void)getJobs {
self.jobs = [[NSMutableArray alloc]init];
self.objectIds = [[NSMutableArray alloc]init];
PFQuery *query = [PFQuery queryWithClassName:#"Completed"];
[query setLimit:1000];
[query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
if (!error) {
for (NSDictionary *objectDictionary in objects) {
[self.jobs addObject:objectDictionary];
for (int i = 0; i < self.jobs.count; i++) {
[self.objectIds addObject:[self.jobs valueForKeyPath:#"objectId"]];
}
}
dispatch_async(dispatch_get_main_queue(), ^ {
[self.tableView reloadData];
[self.loadingIndicator stopAnimating];
});
}
else {
NSLog(#"Error: %# %#", error, [error userInfo]);
}
}];
}
- (void)refreshData {
[self getJobs];
[self.refresh endRefreshing];
}
#pragma mark - Table view data source
- (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.
return self.jobs.count;
}
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
if (editingStyle == UITableViewCellEditingStyleDelete) {
NSString *objectId = [self.objectIds objectAtIndex:indexPath.row];
PFQuery *query = [PFQuery queryWithClassName:#"Completed"];
[query getObjectInBackgroundWithId:objectId block:^(PFObject *job, NSError *error) {
[job deleteInBackground];
}];
[self getJobs];
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"UITableViewCell"];
NSDictionary *jobDictionary = [self.jobs objectAtIndex:[indexPath row]];
if (cell == nil) {
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:#"UITableViewCell"];
}
if (cell) {
cell.backgroundColor = [UIColor clearColor];
cell.textLabel.textColor = [UIColor blackColor];
cell.textLabel.text = [jobDictionary objectForKey:#"job"];
NSString *completedBy = [jobDictionary objectForKey:#"completedBy"];
NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
formatter.dateStyle = NSDateFormatterLongStyle;
formatter.timeStyle = NSDateFormatterShortStyle;
NSString *completedDate = [formatter stringFromDate:[jobDictionary objectForKey:#"date"]];
NSString *detailString = [NSString stringWithFormat:#"Completed by: %# on %#", completedBy, completedDate];
cell.detailTextLabel.text = detailString;
}
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
}
#end
I am trying to have a custom inset for the separator in a UITableView. Here is my code for viewDidLoad
- (void)viewDidLoad {
[super viewDidLoad];
[self.tableView registerClass:[ChatTableCell class] forCellReuseIdentifier:#"ChatCell"];
[self.tableView setSeparatorInset:UIEdgeInsetsMake(0, 65, 0, 0)];
}
The cell separator inset does not work properly as shown in the picture. It works for some cells and does not for others. What am I doing wrong here?
This is what my viewcontroller.m file looks like
#import "ChatListViewController.h"
#interface ChatListViewController ()
#end
#implementation ChatListViewController
- (id)initWithStyle:(UITableViewStyle)style {
//self = [super initWithStyle:style];
self = [super initWithStyle:UITableViewStylePlain];
if (self) {
self.parseClassName = kChatRoomClassKey;
self.paginationEnabled = YES;
self.pullToRefreshEnabled = YES;
self.objectsPerPage = 25;
//[self.tableView setSeparatorInset:UIEdgeInsetsMake(0, 65, 0, 0)];
}
return self;
}
- (PFQuery *)queryForTable {
if (![PFUser currentUser]) {
PFQuery *query = [PFQuery queryWithClassName:self.parseClassName];
[query setLimit:0];
return query;
}
PFQuery *query = [PFQuery queryWithClassName:self.parseClassName];
[query whereKey:kChatRoomUsersKey equalTo:[PFUser currentUser]];
[query includeKey:kChatRoomUsersKey];
[query orderByDescending:#"updatedAt"];
[query setCachePolicy:kPFCachePolicyCacheThenNetwork];
// If no objects are loaded in memory, we look to the cache first to fill the table
// and then subsequently do a query against the network.
//
// If there is no network connection, we will hit the cache first.
if (self.objects.count == 0 || ![[UIApplication sharedApplication].delegate performSelector:#selector(isParseReachable)]) {
[query setCachePolicy:kPFCachePolicyCacheThenNetwork];
}
return query;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath object:(PFObject *)object {
static NSString *CellIdentifier = #"ChatCell";
ChatTableCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[ChatTableCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
[cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
[cell setSelectionStyle:UITableViewCellSelectionStyleGray];
}
cell.selectionStyle = UITableViewCellSelectionStyleNone;
NSArray *users = [object objectForKey:kChatRoomUsersKey];
PFUser *cellUser = (PFUser *)[users objectAtIndex:0];
if ([cellUser.objectId isEqualToString:[PFUser currentUser].objectId]) {
cellUser = [users objectAtIndex:1];
NSLog(#"%#", cellUser);
}
cell.textLabel.font = [UIFont fontWithName:kDefaultFontKey size:17.0];
cell.detailTextLabel.font = [UIFont fontWithName:kDefaultFontLightKey size:14];
if ([cellUser isEqual:[NSNull null]]) {
cell.username.text = #"Selfie User";
cell.textLabel.font = [UIFont fontWithName:kDefaultFontKey size:17.0];
cell.latestText.text = [object objectForKey:kChatRoomLatestTextKey];
cell.detailTextLabel.font = [UIFont fontWithName:kDefaultFontKey size:10.0];
[cell.avatarImageView.profileImageView setImage:[UIImage imageNamed:#"AvatarPlaceholder.png"]];
}
else {
cell.username.text = cellUser.username;
cell.textLabel.font = [UIFont fontWithName:kDefaultFontKey size:17.0];
cell.latestText.text = [object objectForKey:kChatRoomLatestTextKey];
cell.detailTextLabel.font = [UIFont fontWithName:kDefaultFontKey size:10.0];
if ([[cellUser fetchIfNeeded] objectForKey:kPAPUserProfilePicSmallKey] == nil) {
[cell.avatarImageView.profileImageView setImage:[UIImage imageNamed:#"AvatarPlaceholder.png"]];
}
else
[cell.avatarImageView setFile:[cellUser objectForKey:kPAPUserProfilePicSmallKey]];
}
return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
return 70.0f;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
PFObject *chatRoomObject = [self.objects objectAtIndex:indexPath.row];
if ([[chatRoomObject objectForKey:kChatRoomReadKey] isEqual:#NO]) {
[chatRoomObject setObject:#YES forKey:kChatRoomReadKey];
[chatRoomObject saveEventually];
UITabBarItem *tabBarItem = [[self.tabBarController.viewControllers objectAtIndex:PAPFriendsTabBarItemIndex] tabBarItem];
NSString *currentBadgeValue = tabBarItem.badgeValue;
if (currentBadgeValue && currentBadgeValue.length > 1) {
NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
NSNumber *badgeValue = [numberFormatter numberFromString:currentBadgeValue];
NSNumber *newBadgeValue = [NSNumber numberWithInt:[badgeValue intValue] - 1];
tabBarItem.badgeValue = [numberFormatter stringFromNumber:newBadgeValue];
} else {
tabBarItem.badgeValue = #"";
}
}
ChatViewController *convoVC = [[ChatViewController alloc] init];
NSArray *users = [[self.objects objectAtIndex:indexPath.row] objectForKey:kChatRoomUsersKey];
PFUser *cellUser = (PFUser *)[users objectAtIndex:0];
if ([cellUser.objectId isEqualToString:[PFUser currentUser].objectId]) {
cellUser = [users objectAtIndex:1];
}
[convoVC setUser:cellUser];
[convoVC setChatRoom:[self.objects objectAtIndex:indexPath.row]];
[self.navigationController pushViewController:convoVC animated:YES];
}
- (void)viewDidLoad
{
[super viewDidLoad];
[self.tableView registerClass:[ChatTableCell class] forCellReuseIdentifier:#"ChatCell"];
[self.tableView setSeparatorInset:UIEdgeInsetsMake(0, 65, 0, 0)];
[self.navigationController.navigationBar setBarStyle:UIBarStyleBlack];
[self.navigationItem setTitle:#"Chat"];
//Change Back button text
UIBarButtonItem *backButton = [[UIBarButtonItem alloc]
initWithTitle: #""
style: UIBarButtonItemStyleBordered
target: nil action: nil];
[self.navigationItem setBackBarButtonItem: backButton];
[self.navigationController setDelegate:self];
}
-(void)viewDidAppear:(BOOL)animated {
[self loadObjects];
//Google Analytics screen tracking
id tracker = [[GAI sharedInstance] defaultTracker];
[tracker set:kGAIScreenName
value:#"Chat"];
[tracker send:[[GAIDictionaryBuilder createScreenView] build]];
}
-(void)viewWillAppear:(BOOL)animated {
[Flurry logEvent:#"Viewed Chat" timed:YES];
}
-(void)viewWillDisappear:(BOOL)animated {
[Flurry endTimedEvent:#"Viewed Chat" withParameters:nil];
}
#end
After all my workaround , now fixed in both ios 7 and 8 tested.
-(void)viewDidLayoutSubviews
{
[customTableview setSeparatorInset:UIEdgeInsetsZero];
}
-(void)tableView:(UITableView *)tableView willDisplayCell:(customCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
if ([tableView respondsToSelector:#selector(setSeparatorInset:)]){
[tableView setSeparatorInset:UIEdgeInsetsZero];
}
if ([tableView respondsToSelector:#selector(setLayoutMargins:)]) {
[tableView setLayoutMargins:UIEdgeInsetsZero]; // ios 8 newly added
}
if ([cell respondsToSelector:#selector(setLayoutMargins:)]) {
[cell setLayoutMargins:UIEdgeInsetsZero];
}
}
I have a well-functioning search bar. Only one thing that I want to improve is NSTimer. I don`t know why, but when I start typing, it search me results after some delay.It woks perfectly. But I get for every typed letter 1 API each. It mean that if I put into search bar for example Sudan. I get 5 API instead of 1. Could you someone help me?
Thanks
TableViewControllerTOP.h
#interface TableViewControllerTOP : UITableViewController<UISearchDisplayDelegate, UISearchBarDelegate,UIScrollViewDelegate,UITableViewDataSource, UITableViewDelegate>
{
NSTimer *myTimer;
}
#property (strong, nonatomic) IBOutlet UITableView *MainTable;
#property (nonatomic, strong) UISearchBar *searchBar;
#property (nonatomic, strong) UISearchDisplayController *searchController;
#property (nonatomic, strong) NSMutableArray *searchResults;
#property (nonatomic, retain) NSTimer *myTimer;
#property (nonatomic, assign) BOOL isAscending;
TableViewControllerTOP.m
#interface TableViewControllerTOP ()
#property (strong,nonatomic) NSMutableArray *itemss;
#end
#implementation TableViewControllerTOP
#synthesize myTimer;
#synthesize searchBar;
#synthesize searchController;
#synthesize searchResults;
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
self.isAscending = YES;
UIRefreshControl *refreshControl = [[UIRefreshControl alloc] init]; [refreshControl addTarget:self action:#selector(pulltorefresh) forControlEvents:UIControlEventValueChanged];
self.refreshControl = refreshControl;
PFQuery *query = [PFQuery queryWithClassName:#"Countries"];
query.cachePolicy = kPFCachePolicyIgnoreCache;
[query addDescendingOrder:#"createdAt"];
[query setLimit:10];
[query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
if (!error) {
NSMutableArray *items = [NSMutableArray array];
for (id obj in objects)
{
[items addObject:obj];
}
self.itemss = items;
NSLog(#"%#", objects);
NSLog(#"%lu", (unsigned long)[objects count]);
[_MainTable reloadData];
} else {
NSLog(#"Error: %# %#", error, [error userInfo]);
}
}];
[self searchitems];
}
-(void)searchitems
{
self.searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 44)];
self.tableView.tableHeaderView = self.searchBar;
self.searchController = [[UISearchDisplayController alloc] initWithSearchBar:self.searchBar contentsController:self];
self.searchController.searchResultsDataSource = self;
self.searchController.searchResultsDelegate = self;
self.searchController.delegate = self;
self.searchResults = [NSMutableArray array];
self.tableView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:#"background.png"]];
[self.navigationController.navigationBar setBarTintColor:[UIColor lightGrayColor]];
}
-(void)filterResults:(NSString *)searchTerm {
myTimer = [NSTimer scheduledTimerWithTimeInterval:3.0
target:self
selector:#selector(queryask)
userInfo:_itemss
repeats:NO];
}
-(void)queryask{
PFQuery *queryCapitalizedString = [PFQuery queryWithClassName:#"Countries"];
[queryCapitalizedString whereKey:#"CountryTitle" containsString:[searchBar.text capitalizedString]];
PFQuery *queryLowerCaseString = [PFQuery queryWithClassName:#"Countries"];
[queryLowerCaseString whereKey:#"CountryTitle" containsString:[searchBar.text lowercaseString]];
PFQuery *querySearchBarString = [PFQuery queryWithClassName:#"Countries"];
[querySearchBarString whereKey:#"CountryTitle" containsString:searchBar.text];
PFQuery *finalQuery = [PFQuery orQueryWithSubqueries:[NSArray arrayWithObjects:queryCapitalizedString,queryLowerCaseString, querySearchBarString,nil]];
[finalQuery findObjectsInBackgroundWithTarget:self selector:#selector(callbackWithResult:error:)];
}
- (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;
}
- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString {
[self filterResults:searchString];
return YES;
}
- (void)callbackWithResult:(NSArray *)items error:(NSError *)error
{
if(!error) {
[self.searchResults removeAllObjects];
[self.searchResults addObjectsFromArray:items];
[self.searchDisplayController.searchResultsTableView reloadData];
}
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
if (tableView == self.tableView) {
return self.itemss.count;
} else {
return self.searchResults.count;
}
}
- (void)searchDisplayController:(UISearchDisplayController *)controller didLoadSearchResultsTableView:(UITableView *)tableView
{
tableView.rowHeight = 70.0f;
}
- ( UITableViewCell * ) tableView : ( UITableView * ) tableView cellForRowAtIndexPath : ( NSIndexPath * ) indexPath
{
static NSString *uniqueIdentifier = #"MainCell";
CustomCell3 *cell = nil;
cell = (CustomCell3 *) [self.tableView dequeueReusableCellWithIdentifier:uniqueIdentifier];
if (!cell) {
NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:#"MainCell" owner:nil options:nil];
for (id currentObject in topLevelObjects)
{
if([currentObject isKindOfClass:[CustomCell3 class]])
{
cell = (CustomCell3 *)currentObject;
break;
}
}
}
if (tableView == self.tableView) {
cell.MainTitle.text = [[self.itemss objectAtIndex:indexPath.row] objectForKey:#"CountryTitle"];
cell.DescriptTitle.text = [[self.itemss objectAtIndex:indexPath.row] objectForKey:#"DescriptTitle"];
[cell.FlagTitle setImageWithURL:[NSURL URLWithString:[[self.itemss objectAtIndex:indexPath.row] objectForKey:#"ImaURL"]]
placeholderImage:[UIImage imageNamed:#"placeholder.png"]];
cell.backgroundView = [[UIImageView alloc] initWithImage:[ [UIImage imageNamed:#"background.png"] stretchableImageWithLeftCapWidth:0.0 topCapHeight:5.0] ];
cell.selectedBackgroundView = [[UIImageView alloc] initWithImage:[ [UIImage imageNamed:#"background.png"] stretchableImageWithLeftCapWidth:0.0 topCapHeight:5.0] ];
}
if(tableView == self.searchDisplayController.searchResultsTableView) {
PFObject *searchedUser = [self.searchResults objectAtIndex:indexPath.row];
NSString *content = [searchedUser objectForKey:#"CountryTitle"];
NSString *desco = [searchedUser objectForKey:#"DescriptTitle"];
cell.DescriptTitle.text = desco;
cell.MainTitle.text = content;
NSString *image = [searchedUser objectForKey:#"ImaURL"];
[cell.FlagTitle setImageWithURL:[NSURL URLWithString:image]
placeholderImage:[UIImage imageNamed:#"placeholder.png"]];
cell.backgroundView = [[UIImageView alloc] initWithImage:[ [UIImage imageNamed:#"background.png"] stretchableImageWithLeftCapWidth:0.0 topCapHeight:5.0] ];
cell.selectedBackgroundView = [[UIImageView alloc] initWithImage:[ [UIImage imageNamed:#"background.png"] stretchableImageWithLeftCapWidth:0.0 topCapHeight:5.0] ];
}
return cell;
}
#end
For a way to delay the search, take a look at this SO question:
Delay UISearchbar parsing
A good idea could be to combine this with Logan's suggestion. A search should often not be performed until a minimum of characters have been entered, to avoid too broad searches (not much point performing a search for anything containing "s" in many cases, depending on what you are searching).
Perhaps instead of a timer, you could implement a search bar delegate to run a query after some custom logic, perhaps every 3 letters?
- (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
if ((searchBar.text.length % 3) == 0) {
[self queryAsk];
}
}
Note: This logic isn't the best, and you might want to explore various parameters for when to search, but I think the concept improves over the timer because it would be more based on input. I think it would give you more control.
I have got fully working UISearchDisplayController implied in my UITableView made with Parse.com. Anyway when I put to search for, I always get only results starts with that letter. I want to display every data contains that letter.
For example: I put Om into my search and it searched me only : Oman and Ombudsman . I have in my UITableView also a cell named Community . You see this word also contains om but my search don`t display anything. It displays just words staring with these letters.
Can someone help me? Thank you.
#implementation TableViewController3
#synthesize MainTable;
#synthesize searchBar;
#synthesize searchController;
#synthesize searchResults;
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
if ([segue.identifier isEqualToString:#"showDetaill"]) {
{
DetailViewController3 *sdvc = (DetailViewController3 *)[segue destinationViewController];
if(self.searchDisplayController.active) {
NSIndexPath *indexPath = [[self tableView] indexPathForSelectedRow];
PFObject *object = [self.objects objectAtIndex:indexPath.row];
object = (PFObject *)[[self searchResults]objectAtIndex:[[[[self searchDisplayController]searchResultsTableView]indexPathForSelectedRow]row]];
sdvc.objc = object;
} else {
NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];
PFObject *object = [self.objects objectAtIndex:indexPath.row];
DetailViewController3 *detailViewController = [segue destinationViewController];
detailViewController.objc = object;
}
}
}
}
- (void)viewDidLoad
{
[super viewDidLoad];
self.searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 44)];
self.tableView.tableHeaderView = self.searchBar;
self.searchController = [[UISearchDisplayController alloc] initWithSearchBar:self.searchBar contentsController:self];
self.searchController.searchResultsDataSource = self;
self.searchController.searchResultsDelegate = self;
self.searchController.delegate = self;
self.searchResults = [NSMutableArray array];
self.tableView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:#"background.png"]];
[self.navigationController.navigationBar setBarTintColor:[UIColor lightGrayColor]];
-(void)filterResults:(NSString *)searchTerm {
PFQuery *query = [PFQuery queryWithClassName: #"Countries"];
[query whereKey:#"CountryTitle" hasPrefix:searchTerm];
query.limit = 50;
[query findObjectsInBackgroundWithTarget:self selector:#selector(callbackWithResult:error:)];
}
- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString {
[self filterResults:searchString];
return YES;
}
- (void)callbackWithResult:(NSArray *)celebrities error:(NSError *)error
{
if(!error) {
[self.searchResults removeAllObjects];
[self.searchResults addObjectsFromArray:celebrities];
[self.searchDisplayController.searchResultsTableView reloadData];
}
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
if (tableView == self.tableView) {
return self.objects.count;
} else {
return self.searchResults.count;
}
}
- (void)searchDisplayController:(UISearchDisplayController *)controller didLoadSearchResultsTableView:(UITableView *)tableView
{
tableView.rowHeight = 70.0f;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath object:(PFObject *)object {
NSString *uniqueIdentifier = #"MainCell";
CustomCell3 *cell = nil;
cell = (CustomCell3 *) [self.tableView dequeueReusableCellWithIdentifier:uniqueIdentifier];
if (!cell) {
NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:#"MainCell" owner:nil options:nil];
for (id currentObject in topLevelObjects)
{
if([currentObject isKindOfClass:[CustomCell3 class]])
{
cell = (CustomCell3 *)currentObject;
break;
}
}
}
if (tableView == self.tableView) {
cell.MainTitle.text = [object objectForKey:#"CountryTitle"];
cell.DescriptTitle.text = [object objectForKey:#"DescriptTitle"];
[cell.FlagTitle setImageWithURL:[NSURL URLWithString:[object objectForKey:#"ImaURL"]]
placeholderImage:[UIImage imageNamed:#"placeholder.png"]];
cell.backgroundView = [[UIImageView alloc] initWithImage:[ [UIImage imageNamed:#"background.png"] stretchableImageWithLeftCapWidth:0.0 topCapHeight:5.0] ];
cell.selectedBackgroundView = [[UIImageView alloc] initWithImage:[ [UIImage imageNamed:#"background.png"] stretchableImageWithLeftCapWidth:0.0 topCapHeight:5.0] ];
}
if(tableView == self.searchDisplayController.searchResultsTableView) {
PFObject *searchedUser = [self.searchResults objectAtIndex:indexPath.row];
NSString *content = [searchedUser objectForKey:#"CountryTitle"];
NSString *desco = [searchedUser objectForKey:#"DescriptTitle"];
cell.DescriptTitle.text = desco;
cell.MainTitle.text = content;
NSString *image = [searchedUser objectForKey:#"ImaURL"];
[cell.FlagTitle setImageWithURL:[NSURL URLWithString:image]
placeholderImage:[UIImage imageNamed:#"placeholder.png"]];
cell.backgroundView = [[UIImageView alloc] initWithImage:[ [UIImage imageNamed:#"background.png"] stretchableImageWithLeftCapWidth:0.0 topCapHeight:5.0] ];
cell.selectedBackgroundView = [[UIImageView alloc] initWithImage:[ [UIImage imageNamed:#"background.png"] stretchableImageWithLeftCapWidth:0.0 topCapHeight:5.0] ];
}
return cell;
}
#end
Use - (void)whereKey:(NSString *)key containsString:(NSString *)substring instead of - (void)whereKey:(NSString *)key hasPrefix:(NSString *)prefix
-(void)filterResults:(NSString *)searchTerm {
PFQuery *query = [PFQuery queryWithClassName: #"Countries"];
[query whereKey:#"CountryTitle" containsString:searchTerm];
query.limit = 50;
[query findObjectsInBackgroundWithTarget:self selector:#selector(callbackWithResult:error:)];
}
if you use hasPrefix: then the search results will be elements starting with your search string.
When I type letters into my Search I get lag for about 4secs and can`t do anything. Everything others work good. UISearchDisplayController find me what I want, segue works good . I am not sure if it is about memory or some mistake in my code. Can anyone help me? Thanks
My code
TableViewController.m
#implementation TableViewController
#synthesize colorsTable;
#synthesize searchBar;
#synthesize searchController;
#synthesize searchResults;
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
if ([segue.identifier isEqualToString:#"showDetail"]) {
{
DetailViewController *sdvc = (DetailViewController *)[segue destinationViewController];
if(self.searchDisplayController.active) {
NSIndexPath *indexPath = [[self tableView] indexPathForSelectedRow];
PFObject *object = [self.objects objectAtIndex:indexPath.row];
object = (PFObject *)[[self searchResults]objectAtIndex:[[[[self searchDisplayController]searchResultsTableView]indexPathForSelectedRow]row]];
sdvc.detailItem = object;
} else {
NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];
PFObject *object = [self.objects objectAtIndex:indexPath.row];
DetailViewController *detailViewController = [segue destinationViewController];
detailViewController.detailItem = object;
}
}
}
}
- (void)viewDidLoad
{
[super viewDidLoad];
[self performSelector:#selector(runThisMethod) withObject:nil afterDelay:1.9f];
self.searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 44)];
self.tableView.tableHeaderView = self.searchBar;
self.searchController = [[UISearchDisplayController alloc] initWithSearchBar:self.searchBar contentsController:self];
self.searchController.searchResultsDataSource = self;
self.searchController.searchResultsDelegate = self;
self.searchController.delegate = self;
CGPoint offset = CGPointMake(0, self.searchBar.frame.size.height);
self.tableView.contentOffset = offset;
self.searchResults = [NSMutableArray array];
-(void)filterResults:(NSString *)searchTerm {
[self.searchResults removeAllObjects];
PFQuery *query = [PFQuery queryWithClassName: self.parseClassName];
[query whereKeyExists:#"MestoName"]; //this is based on whatever query you are trying to accomplish
[query whereKey:#"MestoName" containsString:searchTerm];
NSArray *results = [query findObjects];
NSLog(#"%#", results);
NSLog(#"%u", results.count);
[self.searchResults addObjectsFromArray:results];
}
- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString {
[self filterResults:searchString];
return YES;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
if (tableView == self.tableView) {
//if (tableView == self.searchDisplayController.searchResultsTableView) {
return self.objects.count;
} else {
return self.searchResults.count;
}
}
- (void)searchDisplayController:(UISearchDisplayController *)controller didLoadSearchResultsTableView:(UITableView *)tableView
{
tableView.rowHeight = 90.0f;
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath object:(PFObject *)object {
static NSString *uniqueIdentifier = #"colorsCell";
CustomCell *cell = nil;
cell = (CustomCell *) [self.tableView dequeueReusableCellWithIdentifier:uniqueIdentifier];
[cell.imagevieww setImageWithURL:[NSURL URLWithString:[object objectForKey:#"ImageURL"]]
placeholderImage:[UIImage imageNamed:#"placeholder.png"]];
cell.cellTitle.text = [object objectForKey:#"MestoName"];
cell.cellDescript.text = [object objectForKey:#"MestoSubname"];
if (!cell) {
NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:#"colorsCell" owner:nil options:nil];
for (id currentObject in topLevelObjects)
{
if([currentObject isKindOfClass:[CustomCell class]])
{
cell = (CustomCell *)currentObject;
break;
}
}
}
if (tableView == self.tableView) {
cell.cellTitle.text = [object objectForKey:#"MestoName"];
} else {
PFUser *obj2 = [self.searchResults objectAtIndex:indexPath.row];
PFQuery *query = [PFQuery queryWithClassName:#"Mesta"];
PFObject *searchedUser = [query getObjectWithId:obj2.objectId];
NSString *boottext = [searchedUser objectForKey:#"MestoName"];
cell.cellTitle.text = boottext;
NSString *bootsubtext = [searchedUser objectForKey:#"MestoSubname"];
cell.cellDescript.text = bootsubtext;
NSString *bootimage = [searchedUser objectForKey:#"ImageURL"];
[cell.imagevieww setImageWithURL:[NSURL URLWithString:bootimage]];
NSLog(#"Content: %#", boottext);
}
return cell;
}
#end
For everyone, who have the same problem. I have got already the solution. I rewrote all my code and it is finally working.
Here`s the code
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath object:(PFObject *)object {
NSString *uniqueIdentifier = #"MainCell";
CustomCell3 *cell = nil;
cell = (CustomCell3 *) [self.tableView dequeueReusableCellWithIdentifier:uniqueIdentifier];
if (!cell) {
NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:#"MainCell" owner:nil options:nil];
for (id currentObject in topLevelObjects)
{
if([currentObject isKindOfClass:[CustomCell3 class]])
{
cell = (CustomCell3 *)currentObject;
break;
}
}
}
if (tableView == self.tableView) {
cell.MainTitle.text = [object objectForKey:#"CountryTitle"];
cell.DescriptTitle.text = [object objectForKey:#"DescriptTitle"];
[cell.FlagTitle setImageWithURL:[NSURL URLWithString:[object objectForKey:#"ImaURL"]]
placeholderImage:[UIImage imageNamed:#"placeholder.png"]];
};
if(tableView == self.searchDisplayController.searchResultsTableView) {
PFObject *searchedUser = [self.searchResults objectAtIndex:indexPath.row];
NSString *content = [searchedUser objectForKey:#"CountryTitle"];
NSString *desco = [searchedUser objectForKey:#"DescriptTitle"];
cell.DescriptTitle.text = desco;
cell.MainTitle.text = content;
NSString *image = [searchedUser objectForKey:#"ImaURL"];
[cell.FlagTitle setImageWithURL:[NSURL URLWithString:image]
placeholderImage:[UIImage imageNamed:#"placeholder.png"]];
};
return cell;
}