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;
}
Related
I have a uitableview inside of a view controller, and a button underneath of my uitableview. Tapping this button opens a modal view. I've created a "close" button inside my modal using the following code:
modalview.m
- (IBAction)closeButton:(id)sender {
[self dismissViewControllerAnimated:YES completion:nil];
}
However when I tap to dismiss my modal view, all of the data in my uitableview seems to disappear (the uitableview just goes white)? Any idea why this might be, and how can I fix it? Here is how my tableview data is loaded and structured (hope this helps):
ViewController.m
-(void)updateMessages {
self.tableView.dataSource = self;
NSMutableDictionary *viewParams = [NSMutableDictionary new];
[viewParams setValue:#"name" forKey:#"view_name"];
[DIOSView viewGet:viewParams success:^(AFHTTPRequestOperation *operation, id responseObject) {
self.messages = (NSMutableArray *)responseObject;
[self.tableView reloadData];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Failure: %#", [error localizedDescription]);
}];
}
- (void)viewDidLoad {
[super viewDidLoad];
[self updateMessages];
static NSString *ChatTableIdentifier = #"ChatTableViewCell";
static NSString *ChatTableIdentifier2 = #"SwapDetailTableViewCell";
UINib *nib = [UINib nibWithNibName: ChatTableIdentifier bundle:nil];
[self.tableView registerNib:nib forCellReuseIdentifier: ChatTableIdentifier];
UINib *nib2 = [UINib nibWithNibName: ChatTableIdentifier2 bundle:nil];
[self.tableView registerNib:nib2 forCellReuseIdentifier: ChatTableIdentifier2];
self.tableView.dataSource = self;
[self.tableView reloadData];
}
- (int)numberOfSectionsInTableView: (UITableView *)tableview
{
return 1;
}
- (int)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [self.messages count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSDictionary *data = self.messages[indexPath.row];
id swaptime = data[#"swaptime"];
if ([swaptime isKindOfClass:[NSString class]]) {
// There is a valid "swaptime" value
static NSString *ChatTableIdentifier2 = #"SwapDetailTableViewCell";
SwapDetailTableViewCell *cell = (SwapDetailTableViewCell *)[tableView dequeueReusableCellWithIdentifier:ChatTableIdentifier2 forIndexPath:indexPath];
NSString *time = data[#"swaptime"];
cell.startTime.text = time;
NSString *timeEnd = data[#"endswaptime"];
cell.endTime.text = timeEnd;
NSString *costofSwap = data[#"swapvalue"];
cell.swapValue.text = costofSwap;
NSString *fromUsername = data[#"first name"];
cell.fromUser.text = fromUsername;
NSString *pet = data[#"pet's name"];
cell.petsname.text = pet;
NSString *swapStatus = data[#"swapaccepted"];
if ([swapStatus isEqual: #"Yes"]) {
[cell.displayedBar setImage:[UIImage imageNamed:#"greenbar.png"]];
cell.swapTitle.text = #"Accepted!";}
else {
if ([swapStatus isEqual: #""]) {
[cell.displayedBar setImage:[UIImage imageNamed:#"orangecellbar.png"]];
cell.swapTitle.text = #"You have a Request!";}
if ([swapStatus isEqual: #"Requested"]) {
[cell.displayedBar setImage:[UIImage imageNamed:#"orangecellbar.png"]];
cell.swapTitle.text = #"You have a Request!";}
if ([swapStatus isEqual: #"Cancelled"]) {
[cell.displayedBar setImage:[UIImage imageNamed:#"blueecellbar.png"]];
cell.swapTitle.text = #"Cancelled!";}
if ([swapStatus isEqual: #"No"]) {
[cell.displayedBar setImage:[UIImage imageNamed:#"redbar.png"]];
cell.swapTitle.text = #"Declined!";
}
}
return cell;
} else {
static NSString *ChatTableIdentifier = #"ChatTableViewCell";
ChatTableViewCell *cell = (ChatTableViewCell *)[tableView dequeueReusableCellWithIdentifier:ChatTableIdentifier forIndexPath:indexPath];
NSString *userName = data[#"first name"];
cell.sendingUser.text = userName;
NSString *messageBody = data[#"body"];
cell.messageDisplayed.text = messageBody;
NSString *timeReceived = data[#"published at"];
cell.timeStamp.text = timeReceived;
NSString *userInfo = [self.userid objectForKey:#"first name"];
if ([cell.sendingUser.text isEqual: userInfo]) {
cell.messageDisplayed.textAlignment = NSTextAlignmentLeft;
cell.sendingUser.textAlignment = NSTextAlignmentLeft;
[cell.chatBubble setImage:[UIImage imageNamed:#"bubblegrey2.png"]];
} else {
cell.messageDisplayed.textAlignment = NSTextAlignmentRight;
cell.sendingUser.textAlignment = NSTextAlignmentRight;
[cell.chatBubble setImage:[UIImage imageNamed:#"bubbleorange2.png"]];
}
return cell;
}
}
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
[self.tableView setContentOffset:CGPointMake(0, CGFLOAT_MAX)];
}
The problem is probably in your viewDidAppear, try replace:
[self.tableView setContentOffset:CGPointMake(0, CGFLOAT_MAX)];
with:
[self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:[self.messages count]-1 inSection:0] atScrollPosition:UITableViewScrollPositionBottom animated:YES];
or properly calculate the height, probably it's:
self.tableView.contentView.height
I make dictionary in iOS, I get data from JSON url. I have problem with correctly display result of word from SearchBar. For example when I type something in searchBar and click on some result , always display value of first result.
Below I put my screen to present this problem.
On the second screen I click on Ruby on Rails and show me first of result "Objective C", why (Objective C is a first result in JSON file)?
And it's my code: http://pastebin.com/EPVTpF9U
#pragma mark - Navigation
-(void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
if([[segue identifier] isEqualToString:#"pushDetailView"]){
NSIndexPath * indexPath = [self.tableView indexPathForSelectedRow];
DetailViewController *modalVC = (DetailViewController*)segue.destinationViewController;
modalVC.detailArray = [self.finalResultArray objectAtIndex:indexPath.row];
}
}
#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:#"Cell"];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
if(tableView == self.tableView){
return self.finalResultArray.count;
}else{
return self.results.count;
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdetifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdetifier forIndexPath:indexPath];
if(!cell){
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdetifier];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
}
if(tableView == self.tableView){
cell.textLabel.text = [[self.finalResultArray objectAtIndex:indexPath.row] objectForKey:#"expression"];
cell.detailTextLabel.text = [[self.finalResultArray objectAtIndex:indexPath.row] objectForKey:#"meaning"];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
}
else{
cell.textLabel.text = [[self.results objectAtIndex:indexPath.row] objectForKey:#"expression"];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
}
UIView *customColorView = [[UIView alloc] init];
customColorView.backgroundColor = [UIColor colorWithRed:180/255.0
green:138/255.0
blue:171/255.0
alpha:0.5];
cell.selectedBackgroundView = customColorView;
return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[self performSegueWithIdentifier:#"pushDetailView" sender:self];
}
- (void)simpleJsonParsing
{
//-- Make URL request with server
NSHTTPURLResponse *response = nil;
NSString *jsonUrlString = [NSString stringWithFormat:#"https://uidictionary.herokuapp.com/phrases.json"];
NSURL *url = [NSURL URLWithString:[jsonUrlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
//-- Get request and response though URL
NSURLRequest *request = [[NSURLRequest alloc]initWithURL:url];
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];
//-- JSON Parsing
NSArray *result = [[NSJSONSerialization JSONObjectWithData:responseData options:
NSJSONReadingMutableContainers error:nil] objectForKey:#"phrases"];
[self.finalResultArray removeAllObjects];
for (NSMutableDictionary *tmp in result)
{
NSMutableDictionary *temp = [NSMutableDictionary new];
[temp setObject:[tmp objectForKey:#"expression"] forKey:#"expression"];
[temp setObject:[tmp objectForKey:#"meaning"] forKey:#"meaning"];
[self.finalResultArray addObject:temp];
}
if (self.finalResultArray){
[self.tableView reloadData];
}
}
- (void)updateSearchResultsForSearchController:(UISearchController *)searchController {
self.results = [self.finalResultArray filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:#"%K contains[c] %#", #"expression", searchController.searchBar.text]];
NSLog(#"Filterd Array:-%#", self.results);
// hand over the filtered results to our search results table
UITableViewController *tableController = (UITableViewController *)self.searchController.searchResultsController;
tableController.tableView.dataSource = self;
tableController.tableView.delegate = self;
[tableController.tableView reloadData];
}
Just replace Bellow Code :-
self.results = [self.finalResultArray filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:#"%K BEGINSWITH[c] %#", #"expression", searchController.searchBar.text]];
#mechu911
Replace your method with below code.
-(void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
if([[segue identifier] isEqualToString:#"pushDetailView"]){
NSIndexPath * indexPath = [self.tableView indexPathForSelectedRow];
DetailViewController *modalVC = (DetailViewController*)segue.destinationViewController;
modalVC.detailArray = [self.result objectAtIndex:indexPath.row];
}
}
but you have to put check like
if(tableView == self.tableView){
modalVC.detailArray = [self.finalResultArray objectAtIndex:indexPath.row];}
else{modalVC.detailArray = [self.result objectAtIndex:indexPath.row];}
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.
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.
in my app I'm using Parse.com as the holder of the data on a database and SearchBarDisplayController for research. I have prepared a following to prepare for my table in order to send the data cells in another view controller and works perfectly ... Now I am having a problem ...
How can I create a "prepareforsegue" for the SearchDisplayController, to activate the cells of the search results?
In here you can see the code for "Prepare for Segue" (or another Method) that I made and the data to be passed ...
Some Ideas on this? Thanks so much!
#import "Ricerca.h"
#import "Custom.h"
#import "DettagliProfilo.h"
#interface Ricerca () <UISearchDisplayDelegate, UISearchBarDelegate>
#property (nonatomic, strong) NSMutableArray *searchResults;
#end
#implementation Ricerca
#synthesize searchResults;
- (void)viewDidLoad {
[super viewDidLoad];
[self loadObjects];
self.searchResults = [NSMutableArray array];
}
- (id)initWithCoder:(NSCoder *)aDecoder
{
self = [super initWithCoder:aDecoder];
if (self) {
// The className to query on
self.parseClassName = #"_User";
self.pullToRefreshEnabled = YES;
self.paginationEnabled = YES;
self.objectsPerPage = 10;
}
return self;
}
- (PFQuery *)queryForTable {
PFQuery *query = [PFQuery queryWithClassName:self.parseClassName];
//[query whereKeyExists:#"username"];
//[query whereKeyExists:#"email"];
[query orderByAscending:#"username"];
if ([self.objects count] == 0) {
query.cachePolicy = kPFCachePolicyCacheThenNetwork;
}
return query;
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
return (interfaceOrientation == UIInterfaceOrientationPortrait || UIInterfaceOrientationIsLandscape(interfaceOrientation));
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath object:(PFObject *)object {
UITableViewCell *cell = (UITableViewCell *)[self.tableView dequeueReusableCellWithIdentifier:#"Cell"];
if (!cell)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:#"Cell"];
}
// Configure the cell
UIColor *color = [[UIColor alloc] initWithRed:0.0 green:0.0 blue:0.0 alpha:0.0];
cell.detailTextLabel.backgroundColor = color;
cell.textLabel.backgroundColor = color;
if (tableView == self.tableView) {
cell.textLabel.text = [object objectForKey:#"username"];
cell.detailTextLabel.text = [object objectForKey:#"email"];
cell.imageView.image = [UIImage imageNamed:#"unknown"];
PFFile *imageFile = [object objectForKey:#"foto"];
[imageFile getDataInBackgroundWithBlock:^(NSData *data, NSError *error) {
cell.imageView.image =[UIImage imageWithData:data];
}];
}
else if(tableView == self.searchDisplayController.searchResultsTableView) {
PFObject *searchedUser = [self.searchResults objectAtIndex:indexPath.row];
NSString *content = [searchedUser objectForKey:#"username"];
NSString *email = [searchedUser objectForKey:#"email"];
cell.detailTextLabel.text = email;
cell.textLabel.text = content;
cell.imageView.image = [UIImage imageNamed:#"unknown"];
PFFile *imageFile = [searchedUser objectForKey:#"foto"];
[imageFile getDataInBackgroundWithBlock:^(NSData *data, NSError *error) {
cell.imageView.image =[UIImage imageWithData:data];
}];
NSLog(#"Content: %#", content);
}
return cell;
}
- (void)callbackLoadObjectsFromParse:(NSArray *)result error:(NSError *)error {
if (!error) {
[self.searchResults removeAllObjects];
NSLog(#"Successfully fetched %d entries", result.count);
[self.searchResults addObjectsFromArray:result];
[self.searchDisplayController.searchResultsTableView reloadData];
} else {
NSLog(#"Error: %# %#", error, [error userInfo]);
}
}
-(void)filterResults:(NSString *)searchTerm {
[self.searchResults removeAllObjects];
PFQuery *query = [PFUser query];
[query orderByAscending:#"username"];
[query whereKeyExists:#"email"];
[query whereKey:#"username" containsString:searchTerm];
query.cachePolicy = kPFCachePolicyNetworkOnly;
[query findObjectsInBackgroundWithTarget:self selector:#selector(callbackLoadObjectsFromParse:error:)];
}
-(BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString {
[self filterResults:searchString];
return YES;
}
- (void)searchDisplayController:(UISearchDisplayController *)controller didLoadSearchResultsTableView:(UITableView *)tableView
{
tableView.rowHeight = 80.0f; // or some other height
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
if (tableView == self.tableView) {
return self.objects.count;
} else {
return self.searchResults.count;
}
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
if (tableView == self.searchDisplayController.searchResultsTableView) {
[super tableView:tableView didSelectRowAtIndexPath:indexPath];
} else {
[super tableView:tableView didSelectRowAtIndexPath:indexPath];
}
}
- (void)viewDidUnload {
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
}
- (void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
}
- (void)viewWillDisappear:(BOOL)animated {
[super viewWillDisappear:animated];
}
- (void)viewDidDisappear:(BOOL)animated {
[super viewDidDisappear:animated];
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
// Check that a new transition has been requested to the DetailViewController and prepares for it
/*if ([segue.identifier isEqualToString:#"Dettaglio"]){
// Capture the object (e.g. exam) the user has selected from the list
NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];
PFObject *object = [self.objects objectAtIndex:indexPath.row];
DettagliProfilo *detailViewController = [segue destinationViewController];
detailViewController.Dettaglio = object;*/
if ([[segue identifier]isEqualToString:#"Dettaglio"])
{
DettagliProfilo *sdvc = (DettagliProfilo *)[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.Dettaglio = object;
} else {
NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];
PFObject *object = [self.objects objectAtIndex:indexPath.row];
DettagliProfilo *detailViewController = [segue destinationViewController];
detailViewController.Dettaglio = object;
}
}
}
#end