我知道它必须处理启动线程来发出网络请求的丑陋,然后可能调用performSelectorOnMainThread:
用我的委托方法。
我知道怎么做use在进行 iOS 编程时,它效果很好。但是,我想知道如何使其在(例如)命令行实用程序的上下文中工作,其中没有具有事件处理等功能的 UIApplication。
我已经尝试过了,似乎程序在异步调用返回后立即退出,然后才能调用委托方法。我非常想更深入地了解它是如何工作的。
Per the docs http://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSURLConnection_Class/Reference/Reference.html#//apple_ref/doc/uid/20001697-387826,连接的委托方法在连接启动的同一线程上调用。因此,要保持该线程运行,直到连接有时间执行其操作:
int main(int argc, char *argv[])
{
// ...
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:del startImmediately:YES];
CFRunLoopRun(); // Run this run loop, run!
// ...
}
然后,当连接表明它已完成时,委托可以停止运行循环:
- (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());
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)