iOS Parse UISearchBar

127 views Asked by At

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. :'(

1

There are 1 answers

5
RTasche On

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.