我有一个应用程序,可以通过Mac/iPhone的GData ObjC客户端上传到谷歌电子表格。它按原样运行良好。我正在尝试在它自己的线程上获取upload部分,并且我正在尝试在一个新线程上调用upload方法。
看:
-(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.
}如果我忘记了使用单独的线程,那么一切都会正常工作。我是线程编程的新手,所以如果我遗漏了什么,请给我提示!
谢谢!
发布于 2010-05-29 14:12:31
我遇到过这个问题,我有一个解决方案,然而,这个解决方案让我在它工作的时候有点畏缩,但它有某种味道……看起来他们应该是更好的方式。
我怀疑在helper fetchUserSpreadsheetFeed中的某个地方,您正在使用某种形式的NSURLConnection。如果使用异步http请求(在其中为回调函数等设置委托),线程可能会在连接有机会调用这些回调函数之前终止,并静默失败。这是我的解决方案,它使线程保持活动状态,直到回调将一个“finished”变量设置为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请求。您可以尝试的另一种解决方案是简单地使用同步请求,但我也不太喜欢这种解决方案,因为异步调用提供了对连接的更细粒度的控制。
发布于 2010-05-29 16:11:31
https://stackoverflow.com/questions/2933822
复制相似问题