我在表格 View 单元格中滚动到屏幕上时下载图像。出于 UX 原因,我开始在 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
中下载图像。我不会等到 TableView 完成滚动。设置表格 View 单元格后,我开始下载我还没有的图像。但是,在表格 View 停止移动之前,它们似乎没有完全下载。一旦它停止移动,图像几乎立即下载。
是否可以在不被主 UI 线程阻塞的情况下使用 NSURLConnection?或者,有没有一种方法可以在滚动表格 View 时快速下载这些图像。
** 编辑 **
为了证明 NSURLConnection 更慢,我使用 NSThread 在不同的线程中分离一个新的选择器。然后我下载数据并回调到我创建 UIImage 并将其显示在 TableView 中的主线程。这种方法工作得更快。
就我个人而言,我认为 NSURLConnection 被扔进了 UITableView 滚动阻止它的事件循环。
最佳答案
阅读NSDefaultRunLoopMode vs NSRunLoopCommonModes为了很好地解释为什么所有下载委托(delegate)通知都排队,但是在使用主线程时滚动时从这里更改下载:
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request
delegate:self];
为此:
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request
delegate:self
startImmediately:NO];
[connection scheduleInRunLoop:[NSRunLoop currentRunLoop]
forMode:NSRunLoopCommonModes];
[connection start];
关于iphone - NSURLConnection 是否阻塞主/UI 线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3234054/