NSThread - 2

上面讲到用初始化的方式来创建线程,并且很明确地指出每初始化一次创建一个新的线程,这里我们继续用别的方式(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



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值