moving a function to a background thread in objective c

后端 未结 2 1196
有刺的猬
有刺的猬 2021-01-30 07:15

I have a function that returns a string that takes 15 seconds to compute on an iPhone.

I want to be able to run the function on the background thread so that the main t

相关标签:
2条回答
  • 2021-01-30 07:40

    Also to add, sometimes you don't need to use GCD, this one is very simple to use :

    [self performSelectorInBackground:@selector(someMethod:) withObject:nil];
    
    0 讨论(0)
  • 2021-01-30 07:43

    Well that's pretty easy actually with GCD. A typical workflow would be something like this:

    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0ul);
    dispatch_async(queue, ^{
        // Perform async operation
        // Call your method/function here
        // Example:
        NSString *result = [anObject calculateSomething];
        dispatch_async(dispatch_get_main_queue(), ^{
            // Update UI
            // Example:
            self.myLabel.text = result;
        });
    });
    

    For more on GCD you can take a look into Apple's documentation here

    0 讨论(0)
提交回复
热议问题