![](/img/trans.png)
[英]Invalidate/Stop NSTimers associated with custom UITableViewCells when they go offscreen
[英]Cancel NSTimers associated with UITableViewCells when they go offscreen
我实现UITableView
的UIImageView
细胞,其中的每一个通过周期性地刷新本身每5秒NSTimer
。 每个图像都是从后台线程中的服务器加载的,从后台线程我也通过调用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) {
}];
}
willMoveToSuperview:
和/或didMoveToSuperview:
不适用于ios 6.0
从ios 6.0开始,您有以下UITableViewDelegate方法
- (void)tableView:(UITableView *)tableView didEndDisplayingCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
使用此方法可以检测何时从表视图中删除单元格,而不是监视视图本身以查看它何时出现或消失。
如果您正确管理内存并使可重用单元格出列,则可以UITableViewCell
并覆盖其- prepareForReuse
方法以停止计时器。
此外,由于@lnfaziger指出,如果你想立即停止时,将小区从表视图中删除的计时器,也可以覆盖其willMoveToSuperview:
和/或didMoveToSuperview:
方法,检查其superview
参数是nil
-如果它是,正在删除单元格,因此您可以停止计时器。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.