1

myButtonActionメインスレッドで「タスクの進行状況」を示すビューをロードしているときに、バックグラウンドスレッドで実行する必要がある重い計算を実行するメソッドがあります。バックグラウンド スレッドがメソッドの実行を完了するとすぐに、「タスクの進行状況」ビューを削除し、メイン スレッドに別のビューをロードする必要があります。

[self performSelectorInBackground:@selector(myButtonAction) withObject:nil];
[self performSelectorOnMainThread:@selector(LoadView) withObject:nil waitUntilDone:YES];

私が直面している問題は、実行が完了する前にmyButtonAction、実行がLoadView完了することです。実行が完了したLoadView後にのみ実行を開始するようにするにはどうすればよいですか。myButtonAction

注:myButtonAction別のクラスにメソッド定義があります。

4

4 に答える 4

2

グランド セントラル ディスパッチを使用する:

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    [self myButtonAction];
    dispatch_async(dispatch_get_main_queue(), ^{
        [self LoadView];
    });
});

または、メソッドにとどまりたい場合performSelector

[self performSelectorInBackground:@selector(loadViewAfterMyButtonAction) withObject:nil];

どこ

- (void)loadViewAfterMyButtonAction
{
    [self myButtonAction];
    [self performSelectorOnMainThread:@selector(LoadView) withObject:nil waitUntilDone:YES];
}
于 2012-06-27T06:43:41.107 に答える
1

あなたは次のことをする必要があります-

[self performSelectorInBackground:@selector(myButtonAction) withObject:nil];

- (void)myButtonAction {
    //Perform all the background task

   //Now switch to main thread with all the updated data
    [self performSelectorOnMainThread:@selector(LoadView) withObject:nil waitUntilDone:YES];
}

編集-それからあなたは試すことができます-

[self performSelectorInBackground:@selector(buttonActionInBackground) withObject:nil];

 - (void)buttonActionInBackground {
       [self myButtonAction];

       //Now switch to main thread with all the updated data
    [self performSelectorOnMainThread:@selector(LoadView) withObject:nil waitUntilDone:YES];
  }

これで、を変更する必要はありませんmyButtonAction

于 2012-06-27T06:30:29.957 に答える
0

このコードはmyButtonActionの最後に呼び出されると思います。

[self performSelectorOnMainThread:@selector(LoadView) withObject:nil waitUntilDone:YES];

「waitUntilDone:YES」で完了するまで待機すると言ったので、myButtonActionが終了する前にLoadViewが終了するのも不思議ではありません。最後にwaitUntilDone:NOで呼び出します。

この種の問題の簡単な解決策については、[self performSelector:@selector(sel) withObject:obj afterDelay:0.0]またはNSTimerを使用してセレクター呼び出しをメイン実行ループに入れることを検討してください。たとえば、UIの更新が完了するまで待機する場合などです。

于 2012-06-27T06:36:07.070 に答える
0

これらの目的のために、セマフォ デザイン パターンを使用します。

于 2012-06-27T06:45:28.263 に答える