iOS多线程 GCD
创建
dispatch_queue_t otherQ = dispatch_queue_create(“name”, NULL);//NULL默认串行队列
获取主队列
dispatch_queue_t mainQ = dispatch_get_main_queue();
NSOperationQueue *mainQ = [NSOperationQueue mainQueue]; // for object-oriented APIs
插入代码块到队列
dispatch_queue_t queue = ...;
dispatch_async(queue, ^{ });
向主队列插入方法
- (void)performSelectorOnMainThread:(SEL)aMethod
withObject:(id)obj
waitUntilDone:(BOOL)waitUntilDone;
//相当于
dispatch_async(dispatch_get_main_queue(), ^{ /* call aMethod */ });
示例 iOS API 使用多线程
在主线程
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration
//delegate如果设置成self,会在下载时候一直得到下载信息。例如下载了多少字节,下载位置。但是此时只关心下载是否完成。所以设置nil。
delegate:nil
<span style="color:#ff0000;">delegateQueue:[NSOperationQueue mainQueue]];</span>
NSURLSessionDownloadTask *task;
task = [session downloadTaskWithRequest:request
completionHandler:^(NSURL *localfile, NSURLResponse *response, NSErr or *error) {
/* yes, can do UI things directly because this is called on the main queue */ }];
[task resume];
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration]; <span style="color:#ff0000;">// no delegateQueue</span>
NSURLSessionDownloadTask *task;
task = [session downloadTaskWithRequest:request
completionHandler:^(NSURL *localfile, NSURLResponse *response, NSError *error) {
dispatch_async(dispatch_get_main_queue(), ^{ /* do UI things */ });
or [self performSelectorOnMainThread:@selector(doUIthings) withObject:nil waitUntilDone:NO];
}];
[task resume];