美文网首页
使用ReactiveCocoa中遇到UITableViewCel

使用ReactiveCocoa中遇到UITableViewCel

作者: MMD_ | 来源:发表于2017-11-17 14:56 被阅读113次

错误的代码

当我们使用rac的时候在cell中按钮的事件如下写法的时候,由于UITableView的复用机制,就会发现,会调用很多次

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
      MLCoolTeamTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
      [[cell.testBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(id x) {
        NSLog(@"click action");
       }];
      return cell;
}

ReactiveCocoa中,RACSignal的subscribeNext的实现是一种订阅者模式,每次注册都会添加一个订阅者信号量[subscribers addObject:subscriber];,一但触发点击事件,所有订阅者的信号量都会被触发,从而触发多次点击事件。

解决--->避免多次注册点击事件

使用rac_command实现点击事件

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    MLCoolTeamTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    @weakify(self)
    mcell.testBtn.rac_command = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(id input) {
        @strongify(self)
        NSLog(@"click action");
        return [RACSignal empty];
    }];
    return cell;   
}

相关文章

网友评论

      本文标题:使用ReactiveCocoa中遇到UITableViewCel

      本文链接:https://www.haomeiwen.com/subject/jpflvxtx.html