使用scrollViewDidScroll错误EXC_BAD_ACCESS

时间:2014-10-15 16:39:40

标签: ios iphone cocoa-touch uiscrollview uikit

我必须遗漏一些明显的东西,因为我有一个非常简单的应用程序会产生EXC_BAD_ACCESS错误。

我在导航控制器中有第一个视图控制器。 从那里,我用UITableView推送第二个视图控制器。 在第二个视图控制器中,我实现了scrollViewDidScroll委托方法。

当我向下滚动到表格底部,然后返回第一个视图控制器时,我收到一个EXC_BAD_ACCESS错误。

以下是第一个视图控制器的代码:

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor redColor];
    UIButton* button = [[UIButton alloc] initWithFrame:CGRectMake(0, 100, self.view.bounds.size.width, 50)];
    button.autoresizingMask = UIViewAutoresizingFlexibleWidth;
    [button setTitle:@"Push tableView" forState:UIControlStateNormal];
    [button addTarget:self action:@selector(buttonClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:button];
}

- (void) buttonClick {
    [self.navigationController pushViewController:[ViewController2 new] animated:YES];
}

@end

这是第二个视图控制器的代码

@interface ViewController2 () <UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, strong) UITableView* tableView;

@end

@implementation ViewController2

- (void)viewDidLoad {
    [super viewDidLoad];
    self.tableView = [[UITableView alloc] initWithFrame:self.view.bounds];
    self.tableView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    [self.view addSubview:self.tableView];
}

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

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 20;
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    NSLog(@"scroll");
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSString* identifer = @"identifer";
    UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:identifer];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifer];
    }
    cell.textLabel.text = [NSString stringWithFormat:@"Cell %d", indexPath.row];
    return cell;
}

@end

当我注释掉scrollViewDidScroll方法时,或者如果在返回到第一个视图控制器之前我没有滚动到表的末尾,则不会生成错误。

我正在使用XCode 6(使用iOS SDK 8),并已在iOS 7和iOS 8模拟器和物理设备上进行了测试。

这有意义吗?

1 个答案:

答案 0 :(得分:3)

您需要在第二个视图控制器的dealloc方法中将数据源设置为nil并委托UITableView的属性。 UITableView在已经解除分配后向委托发送一些消息。

所以,在你的第二个视图控制器中是这样的:

-(void)dealloc
{
    self.tableView.dataSource = nil;
    self.tableView.delegate = nil;
}