耗时操作

当我们在主线程执行一个循环量很大的操作的时候,这样会造成主线程的拥堵,这样的操作放在主线程会严重影响UI体验,比如下面的这个列子

- (void)viewDidLoad {
    [super viewDidLoad];
    
    //1.获得主线程
    NSThread *mainThread = [NSThread mainThread];
    NSLog(@"%@",mainThread);
    
    //2.获得当前线程
    NSThread *currentThread  = [NSThread currentThread];
    NSLog(@"%@",currentThread);
    
    //3.判断主线程
    //3.1 number  == 1
    //3.2 类方法
    BOOL isMainThreadA = [NSThread isMainThread];
    //3.3 对象方法
    BOOL isMainThreadB = [currentThread isMainThread];
    NSLog(@"%zd---%zd",isMainThreadA,isMainThreadB);
    
    
    UIButton *btn = [[UIButton alloc]initWithFrame:CGRectMake(100, 100, 100, 50)];
    [btn setBackgroundColor:[UIColor blueColor]];
    [btn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btn];
    
}



- (IBAction)btnClick:(id)sender {
    
//    NSLog(@"%@",[NSThread currentThread]);
    
    //耗时操作,不要把耗时操作
    for (NSInteger i = 0; i <100000; i++) {
        NSLog(@"%zd----%@",i,[NSThread currentThread]);
    }
    
}


像这样的耗时操作如果放到了主线程,也就是UI线程,会造成UI卡顿,体验很差

你可能感兴趣的:(耗时操作)