如何在此 NSOperation 实例中调用 NSURLConnection 的委托协议方法?
how to make NSURLConnection's delegate protocol method called in this NSOperation instance?
你好,我在 iOS 测试中完成了这个 QCM。我的选择是B,错了。我希望有人能帮助我理解。先感谢您。
问题如下:
NSURLConnection 实例在并发 NSOperation 的 "start" 方法的实现中创建并启动。
要在这个 NSOperation 实例中调用 NSURLConnection 的委托协议方法,应该更改什么?
-(void)start{
...
_connection = [[NSURLConnection alloc] initWithRequest: request delegate:self startImmediately:NO];
[_connection scheduleInRunloop: [NSRunLoop mainRunLoop] forMode:NSRunLoopCommonModes];
[_connection start];
... }
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
NSLog(@"Called"); }
提供三个答案:
A:将 startImmediately 设置为 YES
B:将此代码包装到 dispatch_async(dispatch_get_current_queue(),^{});
C: 没什么,会调用didReceiveResponse。
此代码示例无需更改(选项 C)。
将 startImmediately
设置为 YES
(选项 A)只会在将连接调度到适当的 运行 循环之前启动连接,这会导致问题。
理论上,您可以将连接的创建分派到主线程(选项 B),从而无需在主 运行 循环上手动安排它。但是您的代码示例(在主 运行 循环中手动安排它)完成了同样的事情,并且是更常见的模式。
最重要的是,您现有的代码示例很好。
你好,我在 iOS 测试中完成了这个 QCM。我的选择是B,错了。我希望有人能帮助我理解。先感谢您。
问题如下: NSURLConnection 实例在并发 NSOperation 的 "start" 方法的实现中创建并启动。
要在这个 NSOperation 实例中调用 NSURLConnection 的委托协议方法,应该更改什么?
-(void)start{
...
_connection = [[NSURLConnection alloc] initWithRequest: request delegate:self startImmediately:NO];
[_connection scheduleInRunloop: [NSRunLoop mainRunLoop] forMode:NSRunLoopCommonModes];
[_connection start];
... }
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
NSLog(@"Called"); }
提供三个答案: A:将 startImmediately 设置为 YES
B:将此代码包装到 dispatch_async(dispatch_get_current_queue(),^{});
C: 没什么,会调用didReceiveResponse。
此代码示例无需更改(选项 C)。
将 startImmediately
设置为 YES
(选项 A)只会在将连接调度到适当的 运行 循环之前启动连接,这会导致问题。
理论上,您可以将连接的创建分派到主线程(选项 B),从而无需在主 运行 循环上手动安排它。但是您的代码示例(在主 运行 循环中手动安排它)完成了同样的事情,并且是更常见的模式。
最重要的是,您现有的代码示例很好。