2010-05-29 72 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