1

我有一个应用程序可以通过 Mac/iPhone 的 GData ObjC 客户端上传到 Google 电子表格。它按原样工作正常。我正在尝试在自己的线程上获取上传部分,并尝试在新线程上调用上传方法。

看:

-(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.
}

如果我忘记使用单独的线程,一切都会按预期进行。我是线程编程的新手,所以如果我遗漏了什么,请告诉我!

谢谢!

4

2 回答 2

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]];
}

}

我对这个解决方案的问题是旋转 while 循环通常不是好的做法。不过,我不确定 runloop 业务的性质,它可能是正常睡眠之类的,但我不确定。

无论如何,您可以尝试一下,看看会发生什么!

注意:我的“WLUtilities”函数只是 NSURLConnection 函数的包装器,用于创建异步 http 请求。您可能会尝试的另一个解决方案是简单地使用同步请求,但我也不太喜欢这种解决方案,因为异步调用提供了对连接的更细粒度的控制。

于 2010-05-29T06:12:30.613 回答
0

使用此答案中的技术:

如何使用 iPhone 将照片上传到服务器?

于 2010-05-29T08:11:31.233 回答