找出NSThread何时完成

时间:2011-05-17 06:57:15

标签: objective-c nsthread

按下按钮时,我需要调用一些功能。我使用[self getamountofdatacenters];来调用这些函数。当我按下按钮时,模拟器会卡住所有功能,这需要5-7秒,所以我试图使用NSThread

[NSThread detachNewThreadSelector:@selector(GETAMOUNTDATACENTERS) 
                         toTarget:self 
                       withObject:nil];

我正在使用不同的函数执行此操作三次,但我想知道NSThread的进度是什么,并在实际完成时捕获它。我怎样才能做到这一点?谢谢。

2 个答案:

答案 0 :(得分:3)

忘记显式线程并使用GCD

dispatch_async(dispatch_get_global_queue(0, NULL), ^{
    [self getNumberOfDataCenters];
    dispatch_sync(dispatch_get_main_queue(), ^{
        // The work is done, do whatever you need.
        // This code is executed on the main thread,
        // so that you can update the UI.
    });
});

答案 1 :(得分:0)

一个选项是在应用程序级别“捕获”线程执行的结束:在发布到备用线程的代码中,在完成时触发NSNotification。在主线程中,您会观察此通知并做出相应的反应。

您还可以使用-isExecuting,-isFinished和-isCancelled检查线程的状态。