我有一个函数 foo(),它在后台线程上调用函数 bar
foo()
{
<pre><code> [self performSelectorInBackground:@selector(bar:) withObject:nil];
</code></pre>
<p>}</p>
<pre><code> bar()
{
//some initialsations
//calling another function
bar1();//also in background
//after bar1() returns
//marking following statement with *
[self performSelectorOnMainThread:@selector(stopActivityIndicator:)withObject:nil wailUntilDone:YES];
}
</code></pre>
bar() 在调用另一个函数之前做了一些事情。 bar() 所做的一切都在后台进行。与此同时,我正在展示 ActivityIndicator。一旦 bar() 中的函数返回,我将调用一个将在 MainThread 上停止 ActivityIndicator 的函数。
现在,我想在调用 stopActivityIndicator() 之前调用 MainThread 中的另一个函数
我该怎么做?
我可以再放一个 [self performSelectorOnMainThread:@selector(functionIWantToCall:)withObject:nil wailUntilDone:YES];
在 * 之前?
最佳答案
您可以分派(dispatch)一个 block 在主线程上运行,并将您需要的任何代码放入该 block :
[[NSOperationQueue mainQueue] addOperationWithBlock:^ {
// Code here
NSLog(@"This is the main thread");
}];
使用您的代码,将变成:
bar()
{
bar1();
[[NSOperationQueue mainQueue] addOperationWithBlock:^ {
[stopActivityIndidator];
[functionIWant];
}];
}
关于multithreading - 在后台和主线程 ios 中执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5216829/