How to dispatch code blocks to the same thread in iOS?

前端 未结 8 1685
广开言路
广开言路 2021-01-31 11:04

Main aspect of the question: It\'s about iOS. Can I somehow dispatch code blocks in a way, that they will all (a) run in background and (b) on the same thread?

8条回答
  •  余生分开走
    2021-01-31 11:20

    If you want to perform a selector in Main Thread, you can use

    - (void)performSelectorOnMainThread:(SEL)aSelector withObject:(id)arg waitUntilDone:(BOOL)wait
    

    and if you want to it to perform in background thread

    - (void)performSelectorInBackground:(SEL)aSelector withObject:(id)object
    

    and if you want to perform in any other thread use GCD(Grand Central Dispatch)

    double delayInSeconds = 2.0;
        dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
        dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
            //code to be executed on the main queue after delay
        });
    

提交回复
热议问题