2012-02-08 104 views
0

以下代码位于cellForRowAtIndexPath内。使用块异步下载

1)我需要以某种方式修改此代码,取消下载或当viewDissapears时的块。我想,我应该首先初始化.h文件中的一个块,然后在cellForRowAtIndexPath中使用它,然后在viewDidDissapear时将其设置为零。 (我不确定这种方法是否正确)。有人可以帮我编辑这段代码吗?

注意:当用户在特定的视图上,以及下面的代码下载一些图像时,用户决定移动到另一个视图。然后我想取消下载在viewDidDissapear方法

dispatch_queue_t concurrentQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);  
    dispatch_async(concurrentQueue, ^{   
     NSData *image = // I will be downloading an URL here    
     //this will set the image when loading is finished 
     dispatch_async(dispatch_get_main_queue(), ^{ 
      // I will be displaying the Downloaded image here 
     }); 
    }); 

回答

0

你不应该等待消失的观点,并在表格视图单元格的prepareForReuse方法取消操作。否则,您可能会在下载完成之前(例如,因为用户做了快速滚动)而看到单元被回收,然后在正确的内容覆盖之前,完成的下载将显示错误的内容。除此之外,您的方法看起来可行。

0

下载的内容已经是异步的,所以其包装与GCD只是事情复杂化。这里有一个可下载的项目,您可以尝试下载,在后台下载图片,并在到达时将它们添加到表格视图中。您可以轻松地添加取消当一个下载对象被释放的下载代码:

https://github.com/mattneub/Programming-iOS-4-Book-Examples/blob/master/p754p772downloader/p754downloader/RootViewController.m

+0

这是使用ASIHTTPRequest? – shajem 2012-02-11 19:11:39

+0

我不知道那是什么。看代码,你可以看到它的用途。这是一个完整的工作项目;所有的代码都在那里。没有技巧。 – matt 2012-02-11 20:49:44