0

Je souhaite exécuter deux blocs les uns après les autres, chacun de leur côté étant exécuté de manière asynchrone.GCD - Comment attendre sur le thread principal pour un rappel asynchrone qui est effectué dans la file d'attente principale

Par exemple

[someMethodWithCompletionHandler:^() { 
    // do something in the completion handler 
}]; 

[anotherMethodWithCompletionHandler:^ { 
    // do something else in the completion handler after the first method completes 
}]; 

Maintenant, je dois « anotherMethodWithCompletionHandler » arriver après « someMethodWithCompletionHandler » Complètes (y compris son gestionnaire d'achèvement)

régulièrement je créerais un dispatch_group et attendre entre les 2 méthodes (Je ne peux pas imbriquer les 2 méthodes dans l'autre gestionnaire de complétion car cela nécessiterait beaucoup de code à déplacer)

Mais le problème est que le premier bloc s appelé dans le thread principal (par la méthode elle-même appelant le bloc dans le thread principal) de sorte que je ne peux pas effectivement dispatch_group bloquer le thread principal.

Ainsi, l'état de fil ressemble à quelque chose comme ça

// main thread here 

[self doFirstPortionOfWork]; 

// main thread here 
[self doSecondPortionOfWork]; 


-(void)doFirstPortionOfWork 
{ 
.. a lot of stuff happening 
    [someMethodWithCompletionHandler:^{ 
    // this is the main thread 
    }]; 
// would like to block the return here until the completion handler finishes 
} 

-(void)doSecondPortionOfWork 
{ 
... a lot of work here 
    [anotherMethodWithCompletionHandler^{ 
    // this is also called into the main thread 
    }]; 
// would like to block the return here until the completion handler finishes 
} 

Alors, comment pourrais-je faire avec des recours à un grand nombre de méthodes imbriquées et être en mesure de bloquer le thread principal jusqu'à ce que tout complet?

Répondre

1

thread principal est le même que la file d'attente principale

Il est impossible d'attendre le thread principal pour les travaux futurs dans cette discussion principale. Vous bloquez le futur travail.

Vous pouvez le faire comme ceci:

[someMethodWithCompletionHandler:^() { 
    // do something in the completion handler 
    [anotherMethodWithCompletionHandler:^ { 
     // do something else in the completion handler after the first method completes 
    }]; 
}]; 
+0

Je ne peux pas le faire parce que je n'ai pas la –

+0

imbrication Je ne comprends pas ce que vous entendez par « _Je ne pas le nesting_ ". – Tricertops

Questions connexes