线程之间的通信

线程之间的通信: demo下载
在一个进程中,线程往往不是孤立存在的,多个线程之间需要经常进行通信;

一个线程传递数据给另一个线程,在一个线程中执行完特定任务后,转到另一个线程中继续执行任务

例如:
网络请求到数据,但是UI没有及时更新。
在子线程的block内执行更新UI操作,控制台一般都会有错误线程输出的

 常用方法:
 
 - (void)performSelectorOnMainThread:(SEL)aSelector withObject:(nullable id)arg waitUntilDone:(BOOL)wait;
 - (void)performSelector:(SEL)aSelector onThread:(NSThread *)thr withObject:(nullable id)arg waitUntilDone:(BOOL)wait;
 - dispatch_async(dispatch_get_main_queue(), ^{
   });

具体例子
1 、 先试试再子线程中修改ui (错误代码)

#import "ViewController.h"

@interface ViewController ()
{
    UILabel * lable;
}

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    lable = [[UILabel alloc] initWithFrame:CGRectMake(0, 100, [UIScreen mainScreen].bounds.size.width, 100)];
    lable.textAlignment = NSTextAlignmentCenter;
    lable.text = @"11111111";
    [self.view addSubview:lable];
    
    UIButton * btn = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.frame = CGRectMake(0, 300, [UIScreen mainScreen].bounds.size.width, 100);
    [btn setTitle:@"点击" forState:UIControlStateNormal];
    [btn setBackgroundColor:[UIColor redColor]];
    [self.view addSubview:btn];
    
    [btn addTarget:self action:@selector(ocClick) forControlEvents:UIControlEventTouchUpInside];
}

- (void)ocClick {
    NSOperationQueue * queue = [[NSOperationQueue alloc] init];
    [queue addOperationWithBlock:^{
        lable.text = [NSString stringWithFormat:@"%@%d",@"改变了",arc4random()%100];
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end

如图 :
在这里插入图片描述
在其它线程中修改lable的text ,点击是无法修改的 ;
会发生闪退:提示在主线程操作 ;

2、修改ocClick 方法 如下 :

- (void)ocClick {
    NSOperationQueue * queue = [[NSOperationQueue alloc] init];
    [queue addOperationWithBlock:^{
        //方法1
        /*
         dispatch_async(dispatch_get_main_queue(), ^{
         lable.text = [NSString stringWithFormat:@"%@%d",@"改变了",arc4random()%100];
         });
         */
        
        //方法2
        [self performSelectorOnMainThread:@selector(changeText) withObject:nil waitUntilDone:YES];
        //方法3
//      [self performSelector:@selector(changeText) onThread:[NSThread mainThread] withObject:nil waitUntilDone:YES];
    }];
}

运行效果 :

在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值