【发布时间】:2013-01-15 11:26:03
【问题描述】:
我正在尝试在后台线程中执行下载。为此,我创建了一个 NSOperationQueue 实例并向其添加一个 NSInvocationOperation 实例。
operationQueue = [NSOperationQueue new];
// set maximum operations possible
[operationQueue setMaxConcurrentOperationCount:1];
NSInvocationOperation *operation = [[NSInvocationOperation alloc] initWithTarget:self
selector:@selector(startBackgroundThread:)
object:data];
[operationQueue addOperation:operation];
[operation release];
现在在 startBackgroundThread 中,我创建了一个新的 NSURLConnection 并将 operationQueue 分派给它。
currentConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:NO];
if (self.operationQueue) {
[currentConnection setDelegateQueue:self.operationQueue];
}
[currentConnection start];
iOS6 中的行为
在 iOS6 上运行良好。 一个线程被创建并且 NSURLConnection 回调它在同一个后台线程上委托。
iOS5 和 iOS5.1 中的行为
创建了一个线程,但没有调用 NSURLConnection 委托。
我是否遗漏了一些需要在 iOS5 中考虑的内容? 我已经阅读了 Apple 提供的文档,但没有提到与此相关的内容。
【问题讨论】:
-
你想下载什么?是网页内容的图片吗?
-
如果在运行循环的线程上启动连接,则不会调用委托。
-
所以在主线程上启动连接,其运行循环将始终运行
-
@pradeepa :我正在下载网页内容,我使用了一个单独的线程,它有自己的运行循环来创建 NSURLConnection。问题是委托在 iOS6 中被调用,但在 iOS5.0 和 5.1 中没有
-
好的,您不必承担创建和管理线程的负担,请参阅我的答案中的 NSURLConnection api,它易于使用。系统将代表您创建所需数量的线程,并利用多核处理器。
标签: iphone ios nsurlconnection nsoperation nsoperationqueue