代码之家  ›  专栏  ›  技术社区  ›  Daddy

线程终止太早

  •  1
  • Daddy  · 技术社区  · 14 年前

    我有一个应用程序可以通过Mac/iPhone的gdata objc客户端上传到谷歌电子表格。它工作得很好。我正在尝试在它自己的线程上获取上载部分,我正在尝试在一个新线程上调用上载方法。

    看:

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

    如果我忘记使用一个单独的线程,所有的工作都会像它应该的那样。我是新来的线程编程,所以如果有什么我错过了,请提示我!

    谢谢!

    2 回复  |  直到 14 年前
        1
  •  0
  •   Tom    14 年前

    我有这个问题,我有一个解决方案,但是,这个解决方案让我在工作的时候有点畏缩,但是它有一些气味…似乎他们应该是更好的方法。

    我怀疑在[helper fetchuser spreadsheetfeed]中,您使用的是某种形式的nsurconnection。如果使用异步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业务的性质,它可能是正常的睡眠和工作,但我不确定。

    无论如何,你可以试试看会发生什么!

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

        2
  •  0
  •   Community CDub    7 年前