ViewController委托和viewWillDisappear计时问题

时间:2012-12-04 21:52:03

标签: ios uiviewcontroller delegates null image-loading

我正在使用Apple的延迟加载器代码示例将图像加载到TableView中。由于视图控制器位于导航堆栈中,因此用户可以快速滚动,然后点击并导航出视图。 VC是IconDownloader类的委托,执行图像下载的类,我在VC dealloc中将IconDownloader委托设置为nil。

但是有一个计时问题,滚动委托scrollViewDidEndDecelerating触发,它会触发图像加载,但是在我的viewWillDisappear触发之间但是图像加载事件已经排队了。当视图消失时,这会导致崩溃,委托也是如此,但IconDownloader无论如何都会触发其委托方法。

按顺序如下:

  1. scrollViewDidEndDecelerating(调用loadImagesForOnscreenRows)
  2. viewWillDisappear
  3. loadImagesForOnscreenRows
  4. 我还在使用respondsToSelector检查IconDownloader中的委托状态,而不是nil。

    所以我最终在viewWillDisappear中设置了一个bool,并将委托设置为nil。然后在loadImagesForOnscreenRows中我检查bool。我觉得有更好的方法可以做到这一点,但我读过的所有内容都表明我正在妥善处理委托。大多数帖子建议不要保留IconDownloader的委托。只是想知道其他人对这个解决方案的看法。谢谢!

    代码:

    - (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
    {
        [self loadImagesForOnscreenRows];
    }
    
    
    - (void)loadImagesForOnscreenRows
    {
        if ([self.entries count] > 0 && !viewIsDisappearing)
        {
            ...
        }
    }
    
    
    - (void)viewWillDisappear:(BOOL)animated {
        [super viewWillDisappear:animated];
        viewIsDisappearing = TRUE;
        self.iconDownloader.delegate = nil;
    }
    

    和IconDownloader NSURL connectionDidFinishLoading:

    // call our delegate and tell it that our icon is ready for display
    if (self.delegate != nil && [self.delegate respondsToSelector:@selector(appImageDidLoad:)])
    {
        [delegate appImageDidLoad:self.indexPathInTableView];
    }
    

1 个答案:

答案 0 :(得分:0)

离开视图控制器时是否取消所有已处理的下载?

我在dealloc方法中做的是:

for all iconDownloaders (I have a list of them){
  iconDownloader.delegate = nil;
  [iconDownloader cancelDownload];
}

其中cancelDownload是iconDownloader类中的方法,类似于:

- (void)cancelDownload
{
  [self.connection cancel]; //NSURLConnection
  self.connection = nil;    
  self.receivedData = nil;  //data collected while downloading in NSURLConnection Delegate Methods
}

我使用这个例子进行了少量修改,它对我来说非常有用。

我同意你的意见中的这句话: “大多数帖子建议不要保留IconDownloader的代理。”