gpt4 book ai didi

ios - performSelectorInBackground 和 detachNewThreadSelector 是如何工作的?

转载 作者:可可西里 更新时间:2023-11-01 03:43:45 32 4
gpt4 key购买 nike

我需要执行异步函数执行,因为它阻塞了主线程,因此 UI 不可用。

看了stackoverflow的题目,知道了异步函数的三种方式。

一个例子:

[NSThread detachNewThreadSelector:@selector(showSpinner:) toTarget:self withObject:self.view];
// or
[self performSelectorInBackground:@selector(showSpinner:) withObject:self.view];
// or
NSInvocationOperation *invOperation = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(showSpinner:) object:self.view];
NSOperationQueue *opQueue = [[NSOperationQueue alloc] init];
[opQueue addOperation:invOperation];
// or
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
dispatch_async(dispatch_get_main_queue(), ^{
[self showSpinner:self.view];
});
});

我的问题是 performSelectorInBackgrounddetachNewThreadSelector 如何返回主线程?你怎么知道他们已经完成了?

最佳答案

几个想法:

  1. 您可能想查看 Migrating Away From Threads并发编程指南 中,它为调度队列和操作队列提出了令人信服的论点,这在同一指南的前面进行了讨论。

  2. 此外,当您深入研究各种异步操作时,请记住,在后台队列/线程中执行耗时操作,但始终将 UI 操作分派(dispatch)回主队列。我之所以提到这一点,是因为您的任务 showSpinner 听起来很像 UI 任务,您永远不想在后台队列/线程中执行它。如果它有一些“昂贵”的非 UI 相关任务,那很好,在后台执行,但要确保将 UI 内容分派(dispatch)回主队列。

  3. 除此之外,还有其他操作队列的形式,例如 block 操作:

    NSOperationQueue *opQueue = [[NSOperationQueue alloc] init];
    [opQueue addOperationWithBlock:^{
    // do some slow stuff in the background here

    // ok, now do UI stuff in the main queue

    [[NSOperationQueue mainQueue] addOperationWithBlock:^{
    [self showSpinner:self.view];
    }];
    }];

    这大致相当于 GCD(调度队列)的再现:

    dispatch_queue_t dispatchQueue = dispatch_queue_create("com.ramshad.app", 0);
    dispatch_async(dispatchQueue, ^{
    // do some slow stuff in the background here

    // ok, now do UI stuff in the main queue

    dispatch_async(dispatch_get_main_queue(), ^{
    [self showSpinner:self.view];
    });
    });

    操作队列和调度队列之间有很多微妙的优缺点(我们不应该在这里讨论,因为它已经在 Stack Overflow 的其他地方讨论了数百次),但两者都可以让你用更少的东西做非常丰富的异步操作比传统的线程编程复杂。

  4. 如果您决定坚持使用线程而不是操作和/或调度队列(我不一定会推荐),您可能需要查看 Threading Programming Guide .

关于ios - performSelectorInBackground 和 detachNewThreadSelector 是如何工作的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15376547/

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