【问题标题】:iOS performSelectorInBackground inside performSelectorInBackgroundiOS performSelectorInBackground 里面 performSelectorInBackground
【发布时间】:2014-05-26 10:22:07
【问题描述】:

似乎函数调用[self updateUI];boo阻塞了。

boo 是在另一个后台线程中运行,还是与下面的代码中的 foo 相同?

[self updateUI];如何不被boo阻塞?

- (void)MainFunction
{
    [self performSelectorInBackground@selector(foo) withObject:nil];
}

- (void)foo
{
    [self performSelectorInBackground@selector(boo) withObject:nil];

    //updaate UI in MainThread
    [self updateUI];
}

- (void)boo
{
    //function here take long time to run;
}

【问题讨论】:

  • 先调用main函数,然后调用foo和boo?

标签: ios multithreading blocking background-thread


【解决方案1】:

在您的代码中似乎您在后台调用 foo,因此 UI 在后台线程中更新,这是不可能的,因为您需要在主线程中执行此操作。无论如何,performSelectorInBackground 有点老了……这样使用dispatcher

- (void)MainFunction
{
    [self foo];
}

- (void)foo
{
    dispatch_async(dispatch_get_global_queue(DISPATCH_PRIORITY_DEFAUL, 0ull), ^{
        [self boo];

        dispatch_async(dispatch_get_main_queue(), ^{
            //updaate UI in MainThread
            [self updateUI];
        };
    };
}

- (void)boo
{
    //function here take long time to run;
}

在这种情况下 updateUI 等待 boo,但如果你想要 updateUI 之前 boo 没关系> 完成:

- (void)foo
{
    dispatch_async(dispatch_get_global_queue(DISPATCH_PRIORITY_DEFAUL, 0ull), ^{
        [self boo];
    };

    [self updateUI];
}

【讨论】:

    【解决方案2】:

    performSelectorInBackground 在新线程上执行选择器。来自苹果docs

    此方法在您的应用程序中创建一个新线程,将您的 如果还没有,应用程序进入多线程模式。方法 aSelector 所代表的必须设置线程环境,就像 你会为你的程序中的任何其他新线程。

    如果您想在同一个后台线程上执行这两个函数,则必须将后台线程(也称为队列)声明为该类的私有成员(以便可以从两个函数访问它)并执行该队列上的选择器

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多