取消与UITableViewCells关联的NSTimers,当它们离开屏幕时

时间:2012-09-03 05:03:15

标签: ios uitableview nstimer

我实现了UITableViewUIImageView个单元格,每个单元格通过NSTimer每5秒定期刷新一次。每个图像都是从后台线程中的服务器加载的,并且从后台线程我也通过调用performSelectorOnMainThread来更新UI,显示新图像。到目前为止一切都很好。

我注意到的问题是线程数随着时间的推移而增加,而UI变得没有响应。因此,如果单元格离开屏幕,我想使NSTimer无效。我应该使用UITableView中的哪些委派方法来有效地执行此操作?

我将NSTimer与每个单元格关联的原因是因为我不希望所有单元格同时发生图像转换。 顺便说一句,有没有其他方法可以做到这一点?例如,是否可以只使用一个NSTimer

(我不能使用SDWebImage,因为我的要求是在从服务器加载的循环中显示一组图像)

//在MyViewController.m

 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
    {
        ...
        NSTimer* timer=[NSTimer scheduledTimerWithTimeInterval:ANIMATION_SCHEDULED_AT_TIME_INTERVAL 
                                                    target:self 
                                                  selector:@selector(updateImageInBackground:) 
                                                  userInfo:cell.imageView 
                                                   repeats:YES];
        ...
    }

- (void) updateImageInBackground:(NSTimer*)aTimer
{  
    [self performSelectorInBackground:@selector(updateImage:)
                       withObject:[aTimer userInfo]];
}  

- (void) updateImage:(AnimatedImageView*)animatedImageView 
{      
    @autoreleasepool { 
        [animatedImageView refresh];
    }
}  

//在AnimatedImageView.m

 -(void)refresh
    {
        if(self.currentIndex>=self.urls.count)
            self.currentIndex=0;

    ASIHTTPRequest *request=[[ASIHTTPRequest alloc] initWithURL:[self.urls objectAtIndex:self.currentIndex]];
    [request startSynchronous];

    UIImage *image = [UIImage imageWithData:[request responseData]];

    // How do I cancel this operation if I know that a user performs a scrolling action, therefore departing from this cell.
    [self performSelectorOnMainThread:@selector(performTransition:)
                       withObject:image
                    waitUntilDone:YES];
}

-(void)performTransition:(UIImage*)anImage
{
    [UIView transitionWithView:self duration:1.0 options:(UIViewAnimationOptionTransitionCrossDissolve | UIViewAnimationOptionAllowUserInteraction) animations:^{ 
        self.image=anImage;
        currentIndex++;
    } completion:^(BOOL finished) {
    }];
}

2 个答案:

答案 0 :(得分:6)

willMoveToSuperview:和/或didMoveToSuperview:无法在ios 6.0上运行

从ios 6.0

,你有以下UITableViewDelegate方法

- (void)tableView:(UITableView *)tableView didEndDisplayingCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
  

使用此方法检测何时从表视图中删除单元格,如   反对监视视图本身以查看它何时出现或   消失。

答案 1 :(得分:4)

如果您正确管理内存并将可重用单元格出列,则可以继承UITableViewCell并覆盖其- prepareForReuse方法以停止计时器。

此外,正如@lnfaziger指出的那样,如果要在从表格视图中删除单元格时立即停止计时器,您还可以覆盖其willMoveToSuperview:和/或didMoveToSuperview:方法并检查如果superview参数为nil - 如果是,则删除单元格,这样就可以停止计时器。

相关问题