gpt4 book ai didi

multithreading - 在后台和主线程 ios 中执行

转载 作者:行者123 更新时间:2023-11-28 23:17:47 25 4
gpt4 key购买 nike

我有一个函数 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() 所做的一切都在后台进行。与此同时,我正在展示 ActivityIndi​​cator。一旦 bar() 中的函数返回,我将调用一个将在 MainThread 上停止 ActivityIndi​​cator 的函数。

现在,我想在调用 stopActivityIndi​​cator() 之前调用 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com