- (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