首页 > 代码库 > 多用GCD,少用performSelect系列方法

多用GCD,少用performSelect系列方法

例如,要延后执行某项任务,可以有下面两种实现方式,而我们应该优先考虑第二种:

// Using performSelect: withObject: afterDelay:

[self performSelector: @selector(dosomething)

    withObject:nil

   waitUntilDone:NO];

// Using dispatch_after

dispatch_time_t time = dispatch_time(DISPATCH_TIME_NOW,(int64_t)(5.0 * NSEC_PER_SEC));

dispatch_after(time, dispatch_get_main_queue(),^(void){

    [self dosomething];  

  });

 

想把任务放在主线程中执行,也可以有下面两种方式,而我们还是应该优先选后者:

// Using performSelectOnMainThread: withObject: waitUntilDone:

[self performSelectOnMainThread:@selector:(dosomething) withObject:nil waitUntilDone:NO];

 

//Using dispatch_async

//(or if waitUntilDone is YES, then dispatch_sync)

dispatch_async (dispatch_get_main_queue(),^{

  [self doSomething];

  });

 

多用GCD,少用performSelect系列方法