线程之间的通信: 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];
}];
}
运行效果 :