【问题标题】:Error EXC_BAD_ACCESS with scrollViewDidScroll使用 scrollViewDidScroll 的错误 EXC_BAD_ACCESS
【发布时间】:2014-12-10 20:01:18
【问题描述】:

我一定遗漏了一些明显的东西,因为我有一个非常简单的应用程序会生成 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 模拟器和物理设备上进行了测试。

这有意义吗?

【问题讨论】:

    标签: ios iphone cocoa-touch uiscrollview uikit


    【解决方案1】:

    您需要在第二个视图控制器的 dealloc 方法中将 UITableView 的数据源和委托属性设置为零。 UITableView 在其已被释放后正在向委托发送一些消息。

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

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

    【讨论】:

    • 我只是不明白为什么 Apple 不将这些属性更新为 weak?!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-20
    • 2012-02-26
    • 2012-04-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多