【问题标题】:NSOperation and NSURLConnection conflictsNSOperation 和 NSURLConnection 冲突
【发布时间】:2013-03-01 06:50:16
【问题描述】:

在单独的线程上运行代码的最佳方式是什么?

 NSInvocationOperation *operationToComplete = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(operationMethod) object:nil];
 NSOperationQueue *queueToStart=[[NSOperationQueue alloc] init];
 [queueToStart addOperation:operationToComplete];

 -(void) operationMethod
 {
   NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&_response error:&_error];
 }

或者:

 NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request
                                                            delegate:self];

我一直在做第二种方式,但对此有点困惑或使用另一种方式来做到这一点。

【问题讨论】:

标签: iphone ios multithreading thread-safety


【解决方案1】:

如果您要调用许多并发请求,则将操作队列与同步请求一起使用会特别有用。操作队列不仅可以轻松指定并发操作,还可以指定maxConcurrentOperationCount 以限制要运行的并发操作数量(如果您要启动一大堆并发操作,这一点很重要,因为您仅限于有多少个服务器可以同时运行)。

如果您需要 NSURLConnectionDataDelegate 方法(出于多种原因中的任何一个,例如您想要更新进度视图,您想要执行一些流操作,您想要能够取消连接等)。

第三种方法是将initWithRequest 方法与NSOperationQueue 结合起来,即将NSURLConnection 包装在它自己的NSOperation 中。这结合了这两种技术,提供了丰富的NSURLConnectionDataDelegate 方法(可取消、进度更新等),以及操作队列的功能(能够将网络请求添加到队列中,您可以为其配置并发度,建立依赖关系之间的操作等),但提供了一个很好的界面。有一些特性可以正确实现这种方法(如果你在NSOperationQueue 中使用它,你必须为NSURLConnection 安排/创建一个运行循环)。因此,如果您想享受这项技术的丰富性而又不会迷失在实现细节中,我可能会建议您使用第三方库,例如 AFNetworking

在回答您“哪个最好”的问题时,这仅取决于您要做什么,因为它们各有利弊。但我更喜欢基于NSOperationNSURLConnection,如果您想简化开发工作,通常建议使用AFNetworking


顺便说一句,你大概可以简化第一个例子:

NSOperationQueue *queue = [[NSOperationQueue alloc] init];

[queue addOperationWithBlock:^{
    NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&_response error:&_error];
}];

【讨论】:

    【解决方案2】:

    使用 Grand Central Dispatch (GCD),您可以在后台运行代码,这也更容易。

        dispatch_async( dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        });
    

    还有NSURLConnection supports two modes of operation: asynchronous and synchronous. Neither uses separate threads at all.

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-09-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多