iOS NSThread


- (void)viewDidLoad {

    [super viewDidLoad];

    // Do any additional setup after loading the view.

    self.view.backgroundColor = [UIColor whiteColor];

    UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];

    button.frame = CGRectMake(100, 100, 100, 100);

    button.backgroundColor = [UIColor blueColor];

    [button setTitle:@"NSThread" forState:UIControlStateNormal];

    [button setTitleColor:[UIColor yellowColor] forState:UIControlStateNormal];

    [self.view addSubview:button];

    [button addTarget:self action:@selector(clickThread) forControlEvents:UIControlEventTouchUpInside];

    self.label = [[UILabel alloc] initWithFrame:CGRectMake(100, 300, 100, 100)];

    self.label.backgroundColor = [UIColor grayColor];

    self.label.textColor = [UIColor orangeColor];

    [self.view addSubview:self.label];

    

    

    

    UIButton *backButton = [UIButton buttonWithType:UIButtonTypeSystem];

    backButton.frame = CGRectMake(50, 50, 50, 50);

    [backButton setTitleColor:[UIColor redColor] forState:UIControlStateNormal];

    [backButton setTitle:@"Back" forState:UIControlStateNormal];

    [self.view addSubview:backButton];

    [backButton addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];

    


}

//NSThread按钮点击方法

- (void)clickThread {

    /*

     //一、手动启动

     NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(caculate) object:nil];

     //执行子线程回调方法

     [thread start];

     */

    //二、自动启动线程

    [NSThread detachNewThreadSelector:@selector(caculate) toTarget:self withObject:nil];

    self.label.text = @"正在计算....";

    

}

//NSThread 开辟的子线程回调方法

- (void)caculate {

#warning mark - 注意

    //NSThread手动开辟的线程要用自动释放池,否则会导致内存泄露

    @autoreleasepool {

        NSLog(@"当前线程:%@,在%d行,是否在主线程:%@",[NSThread currentThread],__LINE__,[NSThread isMainThread] == 1 ? @"" : @"");

        //        NSLog(@"%d行是否在主线程:%d",__LINE__,[NSThread isMainThread] == 1 ? YES : NO);

        _sum = 0;

        for (int i = 0; i < 10000; i++) {

            _sum += i;

            NSLog(@"%d",_sum);

        }

        //从子线程跳回到主线程

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

    }

}


//NSThread 回到主线程回调方法

- (void)toMainThread {

    NSLog(@"当前线程:%@,在%d行,是否在主线程:%@",[NSThread currentThread],__LINE__,[NSThread isMainThread] == 1 ? @"" : @"");

    self.label.text = [NSString stringWithFormat:@"%d",self.sum];

}


- (void)back {

    [self dismissViewControllerAnimated:YES completion:nil];

    

}


@end

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值