(异步)NSURLConnection:下面发生了什么?

Der*_*ick 3 cocoa asynchronous objective-c nsurlconnection

我知道它必须处理启动线程以产生网络请求的丑陋,然后可能performSelectorOnMainThread:使用我的委托方法调用.

我知道如何在进行iOS编程时使用它,并且效果很好.但是,我想知道如何在(例如)命令行实用程序的上下文中使其工作,其中没有事件处理的UIApplication等.

我已经尝试过,似乎程序在异步调用返回后立即退出,然后才能调用委托方法.我非常希望更深入地了解它是如何工作的.

Jos*_*ell 7

根据文档,连接的委托方法在启动连接的同一线程上调用.因此,要保持该线程运行,直到连接有时间执行其中:

int main(int argc, char *argv[])
{   
    // ...
    NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:del startImmediately:YES];
    CFRunLoopRun();    // Run this run loop, run!
    // ...
}
Run Code Online (Sandbox Code Playgroud)

然后委托可以在连接完成后停止运行循环:

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    // This returns control to wherever you called
    // CFRunLoopRun() from, so you can still clean up
    // or do other interesting things.
    CFRunLoopStop(CFRunLoopGetCurrent());
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
    NSLog(@"Error: %@", error);
    CFRunLoopStop(CFRunLoopGetCurrent());
}
Run Code Online (Sandbox Code Playgroud)