上面讲到用初始化的方式来创建线程,并且很明确地指出每初始化一次创建一个新的线程,这里我们继续用别的方式(NSThread下)来创建线程。
1.创建完线程直接(自动)执行:
- (void)buttonClicked:(id)sender
{
//输出当前的线程是什么
NSThread* current = [NSThread currentThread];
NSLog(@"btnClick --- %@", current);
//获取主线程
NSThread* main = [NSThread mainThread];
NSLog(@"main --- %@", main);
//耗时操作
[self createDirectNSThread];
}
- (void)createDirectNSThread
{
[NSThread detachNewThreadSelector:@selector(run:) toTarget:self withObject:@"创建完线程直接(自动)启动"];
}
如图:
3.后台创建线程,自动执行:
- (void)createBackgroundNSThread
{
[self performSelectorInBackground:@selector(run:) withObject:@"后台创建, 自动执行"];
}
- (void)run:(NSString* )str
{
NSThread* current = [NSThread currentThread];
for (int i = 0; i< 10; i++)
{
NSLog(@"run --- %@ --- %@", current, str);
}
}
@end
那这三者有什么样的区别呢? 有待持续去分析和了解。
写了一个小小的例子:参考:http://blog.csdn.net/totogo2010/article/details/8010231
#define kURL @"https://www.baidu.com/img/bd_logo1.png"
#import "LBThreadPracViewController.h"
@interface LBThreadPracViewController ()
@property (nonatomic, strong) UIButton* headbtn;
@end
@implementation LBThreadPracViewController
- (void)viewDidLoad
{
[super viewDidLoad];
_headbtn = [UIButton buttonWithType:UIButtonTypeCustom];
_headbtn.frame = CGRectMake(0, 0, 180, 150);
[_headbtn setCenter:CGPointMake(self.view.center.x, self.view.center.y)];
[_headbtn setBackgroundColor:[UIColor blueColor]];
[_headbtn setTitleColor:[UIColor yellowColor] forState:UIControlStateNormal];
[self.view addSubview:_headbtn];
//定时器延迟5s执行
[NSTimer scheduledTimerWithTimeInterval:5.0f target:self selector:@selector(delayOperation) userInfo:nil repeats:NO];
}
- (void)delayOperation
{
//开辟后台线程作网络请求等等耗时数据操作
NSThread* thread = [[NSThread alloc] initWithTarget:self selector:@selector(downloadImage:) object:kURL];
[thread start];
}
- (void)downloadImage:(NSString* )url
{
NSData* data = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:url]];
UIImage* image = [[UIImage alloc] initWithData:data];
if (image == nil)
{
}
else
{
//主线程刷新UI
[self performSelectorOnMainThread:@selector(updateUI:) withObject:image waitUntilDone:YES];
}
}
- (void)updateUI:(UIImage* )image
{
[_headbtn setBackgroundImage:image forState:UIControlStateNormal];
}
@end