2010-05-29 69 views
1

我有一個應用程序可以通過GData ObjC客戶端上傳到Google Spreadsheets for Mac/iPhone。它工作正常。我試圖在自己的線程上獲取上傳部分,並試圖在新線程上調用上傳方法。NSThread過早終止

看:

-(void)establishNewThreadToUpload { 
    [NSThread detachNewThreadSelector:@selector(uploadToGoogle) toTarget:self withObject:nil]; 
} 

-(void)uploadToGoogle { 
    NSAutoReleasePool *pool = [[NSAutoReleasePool alloc] init]; 
    //works fine 
    [helper setNewServiceWithName:username password:password]; 
    //works fine 
    [helper fetchUserSpreadsheetFeed]; 
    //inside the helper class, fetchUserSpreadsheet feed calls ANOTHER method, which 
    //calls ANOTHER METHOD and so on, until the object is either uploaded or fails 
    //However, once the class gets to the end of fetchUserSpreadsheetFeed 
    //control is passed back to this method, and 
    [pool release]; 
    //is called. The thread terminates and nothing ever happens. 
} 

如果我忘了使用一個單獨的線程,一切就像它應該。我是線程編程的新手,所以如果有什麼我錯過了,請告訴我!

謝謝!

+1

什麼是「線程終止,什麼都沒發生」是什麼意思? – 2010-05-29 05:01:03

回答

0

我有這個問題,我有一個解決方案,但是,解決方案讓我畏縮,因爲它的工作原理,但有些東西聞起來......似乎他們應該是一個更好的方法。

我懷疑[helper fetchUserSpreadsheetFeed]內的某處使用某種形式的NSURLConnection。如果您使用的是異步http請求(您爲回調函數等設置代理),那麼線程可能會在連接有機會調用這些回調函數並導致靜默失敗之前終止。這是我的解決方案,它使線程保持活動狀態,直到回調將「完成」變量設置爲YES。 (我似乎也有麻煩在這些文本框中發佈代碼,所以如果那些圍繞編輯東西跑天使能幫助我在那簡直太好了!)

- (void)fetchFeed { 
//NSLog(@"making request"); 
[WLUtilities makeHttpRequest:self.feedUrlString withHttpHeaders:nil withDelegate:self]; 

//block this thread so it's still alive when the delegates get called 
while(!finished) { 
    [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]]; 
} 

}

我有問題這個解決方案是,旋轉循環通常不是很好的做法。雖然我不確定runloop業務的性質,但它可能會適當地睡眠和東西,但我不確定。

無論如何,你可以嘗試一下,看看會發生什麼!

注意:我的「WLUtilities」函數只是NSURLConnection函數的一個包裝器,用於創建一個異步http請求。您可能嘗試的另一個解決方案是簡單地使用一個同步請求,但是我不喜歡這個解決方案,因爲異步調用對連接提供更好的粒度控制。

+0

湯姆,你是對的。 GData ObjC客戶端異步使用回調選擇器。 fetchSpreadsheetFeed方法永遠不會獲取其回調函數。我會試着給你的解決方案。感謝您的高舉 – Justin 2010-05-29 16:17:37