2011-12-01 232 views
2

當我在NSRunLoop,澄清需要

Logger *logger = [Logger new]; 

    NSURL *url = [NSURL URLWithString:@"http://www.google.com"]; 
    NSURLRequest *request = [NSURLRequest requestWithURL:url]; 

    __unused NSURLConnection *conn = [[NSURLConnection alloc] 
      initWithRequest:request delegate:logger startImmediately:YES]; 

...沒有任何反應。代表方法直到我

[[NSRunLoop currentRunLoop]run]; 

我會認爲startImmediately:YES會做到這一點。

+0

這段代碼是在單獨的線程還是主線程中運行? –

+0

主線我知道 – JAM

+0

你在命令行應用程序或gui應用程序? – bryanmac

回答

4

異步回調需要NSRunLoop。請參閱:

Cocoa: NSURLConnection not attempting an HTTP Request

命令行應用程序沒有默認的NSRunLoop - GUI應用做。

從文檔:http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSURLConnection_Class/Reference/Reference.html

initWithRequest:委託: 返回初始化的URL連接,並開始加載數據的URL請求。

- (id)initWithRequest:(NSURLRequest *)request delegate:(id <NSURLConnectionDelegate>)delegate 

...用於連接才能正常工作,調用線程的run 循環必須在默認的運行循環模式下運行。請參閱 scheduleInRunLoop:forMode:更改運行循環和模式。

+0

Bryan - 你的意思是說GUI應用程序自動獲取'NSRunLoop',而命令行應用程序需要明確聲明它? – JAM

+0

就是這樣。 – Wevah

+0

謝謝先生。確實很有幫助。 – JAM