如何在不阻止UI的情况下重复调用方法?

Tuk*_*ajo 4 recursion objective-c nonblocking ios

非常通用的问题,有没有办法在不阻止UI负载的情况下使用应用程序调用我经常使用的方法?

ger*_*iam 7

您可以使用Grand Central Dispatch:

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, kNilOptions), ^{
    // Call your method.
});
Run Code Online (Sandbox Code Playgroud)

  • 对于那些发现这个问题的人,请务必查看0x7fffffff关于dispatch_apply的答案. (2认同)

Mic*_*lum 5

你肯定想使用Grand Central Dispatch来做这件事,但我想指出GCD有一个方法构建只是为了这种事情.dispatch_apply()在您选择的队列上执行其块指定的次数,当然,跟踪您正在进行的迭代.这是一个例子:

size_t iterations = 10;

dispatch_queue_t queue = dispatch_queue_create("com.my.queue", DISPATCH_QUEUE_SERIAL);

dispatch_apply(iterations, queue, ^(size_t i) {
    NSLog(@"%zu",i);// Off the main thread.

    dispatch_async(dispatch_get_main_queue(), ^{
        // Go back to main queue for UI updates and such
    });
});
Run Code Online (Sandbox Code Playgroud)