UITableView中的SearchBar - 排序数组问题

时间:2015-08-30 15:31:11

标签: objective-c uitableview ios8 predicate searchbar

我正在尝试将搜索栏与我的远程表视图集成,但它无法正常工作。没有错误。我想我犯了一些错误,但我不知道哪个部分,所以我需要你的帮助。

这是我的完整代码:

//
//  MasterViewController.m

#import "MasterViewController.h"
#import "DetailViewController.h"
#import "SDWebImage/UIImageView+WebCache.h"

static NSString *const kConsumerKey = @"a1SNULSPtp4eLQTsTXKKSgXkYB5H4CMFXmleFvqE";

@interface MasterViewController ()<UISearchDisplayDelegate>

@property (nonatomic, assign) NSInteger currentPage;
@property (nonatomic, assign) NSInteger totalPages;
@property (nonatomic, assign) NSInteger totalItems;
@property (nonatomic, assign) NSInteger maxPages;

@property (nonatomic, strong) NSMutableArray *photos;
@property (nonatomic, strong) NSMutableArray *searchResults;

@property (strong, nonatomic) IBOutlet UISearchBar *searchBar;

@end

@implementation MasterViewController

- (void)awakeFromNib {
    [super awakeFromNib];
}

- (void)viewDidLoad {
    [super viewDidLoad];

    self.photos = [NSMutableArray array];
    self.searchResults = [NSMutableArray arrayWithCapacity:[self.photos count]];

}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self loadPhotos:self.currentPage];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table View

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (self.currentPage == self.maxPages
        || self.currentPage == self.totalPages
        || self.currentPage == self.totalPages
        || self.totalItems == self.photos.count) {
        return self.photos.count;
    }else if(tableView == self.searchDisplayController.searchResultsTableView){

        return [self.searchResults count];

    }
    return self.photos.count + 1;
}



- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (self.currentPage != self.maxPages && indexPath.row == [self.photos count] - 1 ) {
        [self loadPhotos:++self.currentPage];
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    UITableViewCell *cell = nil;


    if (indexPath.row == [self.photos count]) {

        cell = [tableView dequeueReusableCellWithIdentifier:@"LoadingCell" forIndexPath:indexPath];
        UIActivityIndicatorView *activityIndicator = (UIActivityIndicatorView *)[cell.contentView viewWithTag:100];
        [activityIndicator startAnimating];

    }else{


        cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];


        if(tableView == self.searchDisplayController.searchResultsTableView) {

            cell.textLabel.text = [self.searchResults objectAtIndex:indexPath.row];

        }

        NSDictionary *photoItem = self.photos[indexPath.row];
        cell.textLabel.text = [photoItem objectForKey:@"name"];
        if (![[photoItem objectForKey:@"description"] isEqual:[NSNull null]]) {
            cell.detailTextLabel.text = [photoItem objectForKey:@"description"];
        }

        [cell.imageView sd_setImageWithURL:[NSURL URLWithString:[photoItem objectForKey:@"image_url"]]
                          placeholderImage:[UIImage imageNamed:@"placeholder.jpg"]
                                 completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
                                     if (error) {
                                         NSLog(@"Error occured : %@", [error description]);
                                     }
        }];
    }

    return cell;
}


#pragma mark UISearchDisplay delegate

- (void)filterContentForSearchText:(NSString*)searchText scope:(NSString*)scope
{

    [self.searchResults removeAllObjects];

    NSPredicate *resultPredicate = [NSPredicate
                                    predicateWithFormat:@"SELF contains[cd] %@",
                                    searchText];

    self.searchResults = [NSMutableArray arrayWithArray:[self.photos filteredArrayUsingPredicate:resultPredicate]];//[self.tableData filteredArrayUsingPredicate:resultPredicate];
}

-(BOOL)searchDisplayController:(UISearchDisplayController *)controller
shouldReloadTableForSearchString:(NSString *)searchString
{
    [self filterContentForSearchText:searchString
                               scope:[[self.searchDisplayController.searchBar scopeButtonTitles]
                                      objectAtIndex:[self.searchDisplayController.searchBar
                                                     selectedScopeButtonIndex]]];

    return YES;
}

- (void)loadPhotos:(NSInteger)page {

    NSString *apiURL = [NSString stringWithFormat:@"https://api.500px.com/v1/photos?feature=editors&page=%ld&consumer_key=%@",(long)page,kConsumerKey];

    NSURLSession *session = [NSURLSession sharedSession];
    [[session dataTaskWithURL:[NSURL URLWithString:apiURL]
            completionHandler:^(NSData *data,
                                NSURLResponse *response,
                                NSError *error) {

                if (!error) {

                    NSError *jsonError = nil;
                    NSMutableDictionary *jsonObject = (NSMutableDictionary *)[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&jsonError];

                    NSLog(@"%@",jsonObject);

                    [self.photos addObjectsFromArray:[jsonObject objectForKey:@"photos"]];

                    self.currentPage = [[jsonObject objectForKey:@"current_page"] integerValue];
                    self.totalPages  = [[jsonObject objectForKey:@"total_pages"] integerValue];
                    self.totalItems  = [[jsonObject objectForKey:@"total_items"] integerValue];

                    dispatch_async(dispatch_get_main_queue(), ^{
                        [self.tableView reloadData];
                    });
                }
            }] resume];
}


- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    DetailViewController *vc = segue.destinationViewController;
    NSIndexPath *indexPath = [self.tableView indexPathForCell:sender];
    vc.StoreList = [_photos objectAtIndex:indexPath.row];



}


@end

1 个答案:

答案 0 :(得分:1)

NSDictionary *photoItem = self.photos[indexPath.row];

以后

NSPredicate *resultPredicate = [NSPredicate predicateWithFormat:@"SELF contains[cd] %@", searchText]; 
self.searchResults = [NSMutableArray arrayWithArray:[self.photos filteredArrayUsingPredicate:resultPredicate]];

这看起来像你尝试使用谓词排序而不是字符串而不是字典。

尝试:

NSPredicate *resultPredicate = [NSPredicate predicateWithFormat:@"SELF.name contains[c] %@", searchText];

另外我建议你阅读this code stylehere一些教程如何实施search

关于你的第二个问题

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell;
if (indexPath.row == [self.photos count]) {
    cell = [tableView dequeueReusableCellWithIdentifier:@"LoadingCell" forIndexPath:indexPath];
    UIActivityIndicatorView *activityIndicator = (UIActivityIndicatorView *)[cell.contentView viewWithTag:100];
    [activityIndicator startAnimating];
} else{
    cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];
    if(tableView == self.searchDisplayController.searchResultsTableView) {
         cell.textLabel.text = [self.searchResults[indexPath.row] valueForKey:@"name"]        } else {
    NSDictionary *photoItem = self.photos[indexPath.row];
    cell.textLabel.text = [photoItem objectForKey:@"name"];
    if (![[photoItem objectForKey:@"description"] isEqual:[NSNull null]]) {
        cell.detailTextLabel.text = [photoItem objectForKey:@"description"];
    }
    [cell.imageView sd_setImageWithURL:[NSURL URLWithString:[photoItem objectForKey:@"image_url"]]
                      placeholderImage:[UIImage imageNamed:@"placeholder.jpg"]
                             completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
                                 if (error) {
                                     NSLog(@"Error occured : %@", [error description]);
                                 }
    }];
}
}
return cell;
}