大家好
我在不使用故事板的情况下使用下面的代码并且运行正常,但是当我写第二个搜索字母时它崩溃了。
任何人都可以帮助我
ViewController.h中的
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController <UITableViewDataSource, UITableViewDelegate>
@property (nonatomic, strong) IBOutlet UITableView *tableView;
@property (retain, nonatomic) IBOutlet UILabel *nameLabel;
@end
ViewController.m中的
#import "ViewController.h"
#import "DetailController.h"
@interface ViewController ()
@end
@implementation ViewController {
NSArray *peopleName;
NSArray *searchResult;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
peopleName = [[NSArray alloc] initWithObjects:@"john", @"Waseem", @"Bruce", @"Ammar", @"Londol", nil];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void)dealloc {
[_nameLabel release];
[super dealloc];
}
//
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if (tableView == self.searchDisplayController.searchResultsTableView) {
return [searchResult count];
} else {
return [peopleName count];
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *identifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier] autorelease];
}
if (tableView == self.searchDisplayController.searchResultsTableView) {
cell.textLabel.text = [searchResult objectAtIndex:indexPath.row];
} else {
cell.textLabel.text = [peopleName objectAtIndex:indexPath.row];
}
return cell;
}
#pragma mark - UISearchDisplayController delegate methods
- (void)filterContentForSearchText:(NSString*)searchText scope:(NSString*)scope
{
NSPredicate *resultPredicate = [NSPredicate
predicateWithFormat:@"SELF contains[cd] %@",
searchText];
searchResult = [peopleName filteredArrayUsingPredicate:resultPredicate];
}
-(BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString
{
[self filterContentForSearchText:searchString
scope:[[self.searchDisplayController.searchBar scopeButtonTitles]
objectAtIndex:[self.searchDisplayController.searchBar
selectedScopeButtonIndex]]];
return YES;
}
@end
崩溃并告诉我这个
cell.textLabel.text = [searchResult objectAtIndex:indexPath.row];
(LLDB) 线程1:EXC_BAD_ACCESS(代码= 2,地址= 0x8)
答案 0 :(得分:0)
使用以下代码段:
#pragma mark - UISearchDisplayController delegate methods
- (void)filterContentForSearchText:(NSString*)searchText scope:(NSString*)scope
{
NSPredicate *resultPredicate = [NSPredicate
predicateWithFormat:@"SELF contains[cd] %@",
searchText];
[searchResult release];
searchResult = [peopleName filteredArrayUsingPredicate:resultPredicate]retain];
}