0

我正在使用ASIHTTPRequest編寫一個簡單的庫,其中我以異步方式獲取 URL。我的問題是我寫的main函數測試我的lib在異步調用完成之前退出。使用ASIHTTPRequest測試異步下載

我對Obj C和iPhone的開發很新,有誰能提出一個 好的方法等待所有的請求在主要的 函數中完成?

目前,我main功能看起來像這樣 -

int main(int argc, char *argv[]) { 
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; 
    IBGApp *ibgapp = [[IBGApp alloc] init]; 
    IBGLib *ibgl = [[IBGLib alloc] initWithUsername:@"joe" andPassword:@"xxx"]; 

    // The two method calls below download URLs async. 
    [ibgl downloadURL:@"http://yahoo.com/" withRequestDelegate:ibgapp andRequestSelector:@selector(logData:)]; 
    [ibgl downloadURL:@"http://google.com/" withRequestDelegate:ibgapp andRequestSelector:@selector(logData:)]; 

    [pool release]; 
    return 0; // I reach here before the async calls are done. 
} 

那麼什麼是等待,直到異步調用完成的最好方法?我試着睡覺,但顯然不起作用。

回答

1

簡單和骯髒的解決方案是在[池釋放]之前添加一個循環;線。 STH。像這樣:

while(1){ 
    if ([ibgl requests_finished]){ 
     break; 
    } 
} 

當然,你將需要requests_finished布爾添加到IBGLib類,並使其真(是),當下載完成。記得在請求中處理失敗:)。

2

您也可以告訴ASIHTTPRequest對象同步執行這些請求。

[request startSynchronous]; 
+0

而這是最好的主意:)。 – Jacek 2010-05-26 07:42:07