2015-08-30 54 views
-1

我试图将搜索栏与我的远程表视图集成,但它无法正常工作。没有错误。我想我犯了一些错误,但我不知道哪一部分,所以我需要你的帮助。UITableView中的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 
+0

定义“隐而不宣”工作“。过滤器后的searchResults中有什么? – Larme

+0

你必须详细说明。当你说“不起作用”时,可以有很多方法。我们必须知道它是如何工作的。 –

+0

Im new我只是想用搜索栏搜索“[photoItem objectForKey:@”name“]”例子:我在“Revelation”里面写了搜索栏,没有任何显示,只有Revelation项目 – user3675708

回答

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; 
} 
+0

我改变它,但同样发现他们在控制台,但不细胞 – user3675708

+0

改变了你的代码和同样显示在控制台发现不在tableview中更改找到的项目。 – user3675708