iOS多线程使用实例(异步下载图片的时候不会阻塞主线程的执行)

异步下载图片

  开辟线程 去执行另外一个任务 执行完毕 主线程里面的需要的数据 的再次更新 每一个线程都是独立的代码片片段  当主线程触发下载任务 开辟另一个线程的时候 主线程会继续执行 子线程也会独立执行

  使用alloc init 必须手动启动线程

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

    thread.name = @"下载图片线程";

    [thread start];

或者使用

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

具体代码如下

#import "ViewController.h"


@interface ViewController ()

{

    UIImageView *imageView ;


}

@end


@implementation ViewController


- (void)viewDidLoad {

    [super viewDidLoad];

    self.view.backgroundColor = [UIColor grayColor];

    imageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 100, 100)];

    imageView.layer.cornerRadius = 50;

    imageView.layer.masksToBounds = YES;

    imageView.backgroundColor = [UIColor whiteColor];

    [self.view addSubview:imageView];

    

    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(changePoint:)];

    [self.view addGestureRecognizer:tap];

    

    UIButton *button = [UIButton buttonWithType:0];

    button.frame = CGRectMake(0, 20, 100, 30);

    [button setTitle:@"下载图片" forState:UIControlStateNormal];

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

    [self.view addSubview:button];

}

- (BOOL)prefersStatusBarHidden

{

    return YES;

}

- (void)changePoint:(UITapGestureRecognizer *)sender

{

    获取当前线程[NSThread currentThread]

    NSLog(@"点击线程:%@",[NSThread currentThread]);

    imageView.center = [sender locationInView:self.view];

}


- (void)downLoadImage:(UIButton *)sender

{

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

    thread.name = @"下载图片线程";

    [thread start];


}


- (void)downLoadOperation

{

    NSLog(@"下载线程:%@",[NSThread currentThread]);

    模拟 下载的耗时任务的操作

    sleep(3);

    

    NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://img.xgo-img.com.cn/pics/1505/1504430.jpg"]];

    当操作完毕之后刷新ui 在主线程里面去刷新

    从子线程回到主线程去刷新页面

    [self performSelectorOnMainThread:@selector(updataUI:) withObject:data waitUntilDone:YES];

}

- (void)updataUI:(NSData *)datas

{

    NSLog(@"刷新线程:%@",[NSThread currentThread]);

    imageView.image = [UIImage imageWithData:datas];

}


@end


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值