GCD为什么不能在子线程更新UI

来源:互联网 发布:appstore淘宝下载不了 编辑:程序博客网 时间:2024/04/28 12:27
以前也只是听说子线程下不能更新UI ,但不知道为什么今天手写了一个demo终于找的了答案
#import "AlexViewController.h"#import "AlexTwoViewCoViewController.h"@interface AlexViewController (){UIView *aa;}@property (weak, nonatomic) IBOutlet UIButton *button;@end@implementation AlexViewController- (IBAction)click:(id)sender {dispatch_queue_t serialQueue1 = dispatch_queue_create("com.SerialQueue1", NULL);dispatch_queue_t serialQueue2 = dispatch_queue_create("com.SerialQueue2", NULL);dispatch_async(serialQueue1, ^{NSLog(@"2222%@",serialQueue1);aa.frame = CGRectMake(50, 50, 50, 50);});dispatch_async(serialQueue2, ^{NSLog(@"33333%@",serialQueue2);aa.backgroundColor = [UIColor yellowColor];});}- (void)viewDidLoad{    [super viewDidLoad];aa = [[UIView alloc] initWithFrame:CGRectMake(100, 100, 100, 100)];aa.backgroundColor = [UIColor purpleColor];[self.view addSubview:aa];_button.backgroundColor = [UIColor redColor];}

我在storyboard拖了一个button,写了一个点击事件click,目的是要更新View的大小坐标和View的背景,当点击后发现没有什么反应 直到过了5秒以后才更新了UI.原来并不是子线程无法更新UI,而是会卡主线程,所以正确做法是更新UI的时候切换到主线程

- (IBAction)aaa:(id)sender {dispatch_queue_t serialQueue1 = dispatch_queue_create("com.SerialQueue1", NULL);dispatch_queue_t serialQueue2 = dispatch_queue_create("com.SerialQueue2", NULL);dispatch_async(serialQueue1, ^{NSLog(@"2222%@",serialQueue1);dispatch_async(dispatch_get_main_queue(), ^{aa.frame = CGRectMake(50, 50, 50, 50);});});dispatch_async(serialQueue2, ^{NSLog(@"33333%@",serialQueue2);dispatch_async(dispatch_get_main_queue(), ^{aa.backgroundColor = [UIColor yellowColor];});});}
这是点击事件的修改后 更新UI切换到主线程执行,就不会出现卡顿的问题喽


0 0