问题:Object C中创建线程的方法是什么?如果在主线程中执行

2020-05-18  本文已影响0人  姜小舟

线程创建有三种方法:

NSThread *oneThread=[[NSThread alloc]initWithTarget:self selector:@selector(sayMethod) object:nil];
[oneThread start];
#还可以是 
[self performSelectorInBackground:@selector(sayMethod) withObject:nil];
#也可以是
[NSThread detachNewThreadSelector:@selector(sayMethod) toTarget:self withObject:nil];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    [NSThread sleepForTimeInterval:3];
    NSString *str=@"nice to meet you";
    NSLog(@"%@",str);
    dispatch_async(dispatch_get_main_queue(), ^{
        UILabel *onelabel=[[UILabel alloc]initWithFrame:CGRectMake(100, 100, 100, 100)];
        [self.view addSubview:onelabel];
        onelabel.text=str;
    });
});
#模仿下载网络图像
- (IBAction)operationDemo3:(id)sender {
   // 1\. 下载
  NSBlockOperation *op1 = [NSBlockOperation blockOperationWithBlock:^{
      NSLog(@"下载 %@" , [NSThread currentThread]);
  }];
  // 2\. 滤镜
  NSBlockOperation *op2 = [NSBlockOperation blockOperationWithBlock:^{
       NSLog(@"滤镜 %@" , [NSThread currentThread]);
    }]; 
   // 3\. 显示
   NSBlockOperation *op3 = [NSBlockOperation blockOperationWithBlock:^{
       NSLog(@"更新UI %@" , [NSThread currentThread]); 
   }]; 
   // 添加操作之间的依赖关系,所谓“依赖”关系,就是等待前一个任务完成后,后一个任务才能启动   
   // 依赖关系可以跨线程队列实现 
   // 提示:在指定依赖关系时,注意不要循环依赖,否则不工作。
   [op2 addDependency:op1]; 
   [op3 addDependency:op2]; 
//    [op1 addDependency:op3];

   [_queue addOperation:op1]; 
   [_queue addOperation:op2]; 
   [[NSOperationQueue mainQueue] addOperation:op3]; 
}

在主线程执行代码,方法是performSelectorOnMainThread

[self performSelectorOnMainThread:@selector(refreshTableView) withObject:nil waitUntilDone:YES];

如果想延时执行代码可以用performSelector:onThread:withObject:waitUntilDone

[self performSelector:@selector(test:) onThread:thread withObject:nil waitUntilDone:NO];
上一篇 下一篇

猜你喜欢

热点阅读