(异步)NSURLConnection的:这是怎么回事底下? [英] (Asynchronous) NSURLConnection: what's going on underneath?

查看:147
本文介绍了(异步)NSURLConnection的:这是怎么回事底下?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我明白,它必须考虑推出一个线程使网络请求,则可能调用的丑陋照顾performSelectorOnMainThread:我的委托方法。

I understand that it must be taking care of the ugliness of launching a thread to make the network request, then probably calling performSelectorOnMainThread: with my delegate method.

我知道如何的使用的做iOS的编程,当它和它的伟大工程。不过,我想知道我将如何使它工作的背景下做(比如)一个命令行工具,其中有一个与事件处理没有任何的UIApplication等。

I know how to use it when doing iOS programming, and it works great. However, I'd like to know how I would make it work doing in the context of (for example) a command line utility, where there is no UIApplication with the event processing etc.

我试了一下,似乎计划尽快异步调用返回退出,委托方法可以被调用之前。我pretty很想它是如何工作有更深的了解。

I've tried it, and it seems that the program exits as soon as the asynchronous call returns, before the delegate methods can get called. I pretty much want a deeper understanding of how it works.

推荐答案

按照<一个href=\"http://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSURLConnection_Class/Reference/Reference.html#//apple_ref/doc/uid/20001697-387826\">docs,连接的委托方法被调用该连接从开始在同一线程上。因此,要保持该线程运行,直到连接有时间做它的东西:

Per the docs, the connection's delegate methods get called on the same thread that the connection was started from. So, to keep that thread running until the connection has time to do its stuff:

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

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

Then the delegate can stop the run loop when the connection says it's finished:

- (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());
}

这篇关于(异步)NSURLConnection的:这是怎么回事底下?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆