【问题标题】:ASynchronous NSURLConnection inside NSOperation with NSInvocation?NSOperation 中的异步 NSURLConnection 与 NSInvocation?
【发布时间】:2012-02-10 10:23:15
【问题描述】:

我必须在后台模式下在 NSOPeration 中使用 Asynchrnous NSURLConnection,因为它的响应有大数据我必须避免在 didEnterBackground 中使用 Apple 的有限长度编码。我通过 NSOperation 使用以下代码和 NSInvocation 作为,但它是不工作。connectToServer 正在进行 NSURLConnection 操作。有什么帮助吗?didReceiveData,didReceiveResponse 委托方法没有被调用?

 -(void)viewDidLoad
 {
 NSOperationQueue *queue = [NSOperationQueue new];

NSInvocationOperation *operation = [[NSInvocationOperation alloc] initWithTarget:self
                                                                        selector:@selector(connectServer)
                                                                          object:nil];

[queue addOperation:operation];
[operation release];
[queue autorelease];

}

 -(void)connectServer
{


NSURL *url = [NSURL URLWithString:@"http://www.google.com"];
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url];
NSURLConnection *theConnection = [[[NSURLConnection alloc] initWithRequest:theRequest delegate:self] autorelease];

    if( theConnection )
    {
        webData = [[NSMutableData data] retain];
    }
    else
    {
        NSLog(@"theConnection is NULL");
    }
}

}

【问题讨论】:

标签: objective-c ios nsurlconnection nsoperation nsinvocation


【解决方案1】:

mmmm 也许你可以在主队列的块内进行连接:

dispatch_async(dispatch_get_main_queue(), ^{

        NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url cachePolicy:NSURLRequestReturnCacheDataElseLoad timeoutInterval:10.0];
        _connection = [[NSURLConnection alloc] initWithRequest:request startImmediately:YES];
        [request release];
});

然后应该调用委托方法。

【讨论】:

    【解决方案2】:

    当你想在辅助线程上运行 NSURLConnection 时,你需要将该连接添加到 runloops

    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    
        NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url 
                    cachePolicy:NSURLRequestReturnCacheDataElseLoad timeoutInterval:10.0];
        _connection = [[NSURLConnection alloc] initWithRequest:request delegate:self
                     startImmediately:YES];
        [request release];
    
    
    [_connection scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
    [_connection start];
    
        [pool release];
    

    【讨论】:

      【解决方案3】:

      我可能错了,但我还是会尝试......

      查看文档说...对于start 方法

      start 使连接开始加载数据,如果它还没有 已经。

      • (void)start Discussion 仅当您创建与 initWithRequest:delegate:startImmediately: 方法并为 startImmediately 参数。如果您不安排连接 在调用此方法之前,在运行循环或操作队列中, 连接在当前运行循环中以默认模式调度。

      所以在我看来,您必须手动启动连接,因为它位于操作队列中。 如果我错了,请纠正我。

      【讨论】:

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