iOS多线程 GCD

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];



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值