GCD是基于c的底层api,NSOperation属于object-c类。相对于GCD :
1,NSOperation拥有更多的函数可用,具体查看api。
2,在NSOperationQueue中,可以建立各个NSOperation之间的依赖关系。
3,有kvo,可以监测operation是否正在执行(isExecuted)、是否结束(isFinished),是否取消(isCanceld)。
4,NSOperationQueue可以方便的管理并发、NSOperation之间的优先级。
5,GCD主要与block结合使用。
/ /**< 自定义queue,默认串行: NULL == DISPATCH_QUEUE_SERIAL*/
/**< label:标签,用于标注queue*/
dispatch_queue_t queue = dispatch_queue_create("label", NULL);
dispatch_async(queue, ^{
NSLog(@"test");
});
/**< 自定义queue,并行或串行: DISPATCH_QUEUE_CONCURRENT或DISPATCH_QUEUE_SERIAL*/
dispatch_queue_t serial_queue = dispatch_queue_create("标签", DISPATCH_QUEUE_CONCURRENT);
dispatch_async(serial_queue, ^(){
sleep(5);
NSLog(@"block_1"); // 尽管为异步调用且延迟3秒,但如果在serial队列中,block_1仍然先于block_2被打印出来
});
dispatch_async(serial_queue, ^(){
NSLog(@"block_2");
});
/**< 延迟执行*/
/**< (int64_t)(delayInSeconds * NSEC_PER_SEC):转换成毫秒*/
double delayInSeconds = 5.0;
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
NSLog(@"5s delay");
});
/**< 常用的异步并发执行*/
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT , 0), ^{
sleep(5);
NSLog(@"block_1");
});
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT , 0), ^{
NSLog(@"block_2");
});
/**< 异步并回调主线程,常用ui更新*/
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT , 0), ^{
dispatch_async(dispatch_get_main_queue(), ^{
NSLog(@"to do with ui");
});
});