Objective-C delay action with blocks

后端 未结 4 898
眼角桃花
眼角桃花 2020-12-08 00:12

I know that there are several ways of delaying an action in Objective-C like:

performSelector:withObject:afterDelay:

or using NSTimer

4条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-08 00:56

    Expanding on the accepted answer, I created a Helper function for anyone who doesn't care to memorize the syntax each time they want to do this :) I simply have a Utils class with this:

    Usage:

    [Utils delayCallback:^{
         //--- code here
    } forTotalSeconds:0.3];
    

    Helper method:

    + (void) delayCallback: (void(^)(void))callback forTotalSeconds: (double)delayInSeconds{
    
         dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
         dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
               if(callback){
                    callback();
               }
          });
    }
    

提交回复
热议问题