ios学习(十九)NSThread简单使用

来源:互联网 发布:html源码怎么用 编辑:程序博客网 时间:2024/04/30 12:26

#import "ViewController.h"@interface ViewController ()-(void)printMuch;@property (weak, nonatomic) IBOutlet UIImageView *picImg;@end@implementation ViewController- (IBAction)buttonClicked:(id)sender {//    [self printMuch];//    [self createThread1];//    [self createThread2];//    [self createThread3];//    [self downloadImage];    [NSThread detachNewThreadSelector:@selector(downloadImage) toTarget:self withObject:nil];    }-(void)downloadImage{    NSDate *begin = [NSDate date];    NSURL *url = [NSURL URLWithString:@"https://a-ssl.duitang.com/uploads/item/201504/03/20150403H4808_2QkBX.jpeg"];    NSData *data = [NSData dataWithContentsOfURL:url];    UIImage *image = [UIImage imageWithData:data scale:2];    NSDate *end = [NSDate date];            //通知主线程更新ui//    [self performSelectorOnMainThread:@selector(setDataToImageView:) withObject:image waitUntilDone:YES];    [self performSelector:@selector(setDataToImageView:) onThread:[NSThread mainThread] withObject:image waitUntilDone:YES];        NSLog(@"wo zai deng dai");    NSLog(@"%f", [end timeIntervalSinceDate:begin]);    }-(void)setDataToImageView:(UIImage *)image{    [self.picImg setImage:image];}-(void) createThread1{    NSThread *tread = [[NSThread alloc] initWithTarget:self selector:@selector(printMuch) object:nil];    [tread start];}-(void)createThread2{    [NSThread detachNewThreadSelector:@selector(printMuch) toTarget:self withObject:nil];}-(void)createThread3{    [self performSelectorInBackground:@selector(printMuch) withObject:nil];}-(void)printMuch{    for (NSInteger i = 0; i < 10000; i++){        NSLog(@"%ld", (long)i);    }}- (void)viewDidLoad {    [super viewDidLoad];    // Do any additional setup after loading the view, typically from a nib.}- (void)didReceiveMemoryWarning {    [super didReceiveMemoryWarning];    // Dispose of any resources that can be recreated.}@end


0 0
原创粉丝点击