当执行那些与 UI 无关的任务,或者与 UI 交互的任务时,和执行其他任务一样,会需要大量时间,以上情况会经常出现。我们可以使用 dispatch_sync函数在一个分派队列上执行同步任务。你必须做的事情就是提供一个此队列的句柄了,这个队列必须运行任务,并且一个代码块会在这个队列上执行。 今天我们就来学习一下GCD执行非UI的操作。
TestDemo.h
#import <Foundation/Foundation.h> @interface TestDemo : NSObject -(void)testMethod; -(void)testMethod2; @end
TestDemo.m
#import "TestDemo.h" @implementation TestDemo /**************Objc Method Start*********/ //Block Object void (^printFrom1To1000)(void) = ^{ NSUInteger counter = 0; for (counter = 1;counter <= 1000;counter++){ NSLog(@"Counter = %lu - Thread = %@", (unsigned long)counter, [NSThread currentThread]); } }; //测试方法 -(void)testMethod{ /* Dispatch_get_global_queue 函数的第一个参数说明了并发队列的优先级,这个属性 GCD 必须替程序员检 索。优先级越高,将提供更多的 CPU Timeslice 来获取该队列执行的代码。 Dispatch_get_global_queue 函数的第一个参数: DISPATCH_QUEUE_PRIORITY_LOW 您的任务比正常任务用到更少的 Timeslice。 DISPATCH_QUEUE_PRIORITY_DEFAULT 执行代码的默认系统优先级将应用于您的任务。 DISPATCH_QUEUE_PRIORITY_HIGH 和正常任务相比,更多的 Timeslices 会应用到你的任务中。 Dispatch_get_global_queue 函数的第二个参数已经保存了,只要一直给它输入数值 0 就可以了。 */ dispatch_queue_t concurrentQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); dispatch_sync(concurrentQueue, printFrom1To1000); dispatch_sync(concurrentQueue, printFrom1To1000); } /**************Objc Method End*********/ /**************C Method Start*********/ //Block Object void print2From1To1000(void *paramContext){ NSUInteger counter = 0; for (counter = 1;counter <= 1000;counter++){ NSLog(@"Counter = %lu - Thread = %@", (unsigned long)counter, [NSThread currentThread]); } } //测试方法 -(void)testMethod2{ /* */ dispatch_queue_t concurrentQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); dispatch_sync_f(concurrentQueue, NULL,print2From1To1000); dispatch_sync_f(concurrentQueue, NULL,print2From1To1000); } /**************C Method End*********/ @end
main.m
#import <Foundation/Foundation.h> #import "TestDemo.h" int main(int argc, const char * argv[]) { @autoreleasepool { TestDemo *test = [[TestDemo alloc] init]; // [test testMethod]; [test testMethod2]; [test release]; } return 0; }
运行结果
2013-05-10 13:50:37.361 GCDExecuteNonUITest[556:303] Counter = 1 - Thread = <NSThread: 0x10010b2c0>{name = (null), num = 1}
2013-05-10 13:50:37.363 GCDExecuteNonUITest[556:303] Counter = 2 - Thread = <NSThread: 0x10010b2c0>{name = (null), num = 1}
...2013-05-10 13:50:38.255 GCDExecuteNonUITest[556:303] Counter = 1 - Thread = <NSThread: 0x10010b2c0>{name = (null), num = 1}
2013-05-10 13:50:38.256 GCDExecuteNonUITest[556:303] Counter = 2 - Thread = <NSThread: 0x10010b2c0>{name = (null), num = 1}
以上就是所有内容,希望对大家有所帮助。
Demo代码下载:http://download.csdn.net/detail/u010013695/5352720