iOS开发 NSThread实际使用

//
//  NSThreadViewController.m
//  DemoTest
//
//  Created by biyabi on 15/8/18.
//  Copyright (c) 2015年 test. All rights reserved.
//
#import "NSThreadViewController.h"
#import "HeadFile.h"
#define imageURL @"http://images.cnitblog.com/blog/381483/201408/221614287532594.png"
@interface NSThreadViewController ()
@property (nonatomic, strong) UIImageView *imageView;
@end
@implementation NSThreadViewController
- (void)viewDidLoad {
    [super viewDidLoad];
    [self.view setBackgroundColor:[UIColor whiteColor]];
    self.title = @"NSThread";
    [self initUI];
    
    //创建方式一:
    //    NSThread *thread = [[NSThread alloc]initWithTarget:self selector:@selector(threadRun:) object:imageURL];
    //    [thread start];
    
    //创建方式二:
    [NSThread detachNewThreadSelector:@selector(threadRun:) toTarget:self withObject:imageURL];
    
    //这两个方式随便选择哪个都是可以的
    
}
- (void)threadRun:(NSString *)url{
    NSData *data = [[NSData alloc]initWithContentsOfURL:[NSURL URLWithString:url]];
    UIImage *image = [[UIImage alloc]initWithData:data];
    if (!data) {
        return;
    }
    [self performSelectorOnMainThread:@selector(updataImage:) withObject:image waitUntilDone:YES];
}
- (void)updataImage:(UIImage *)image{
    [self.imageView setImage:image];
}
- (void)initUI{
    self.imageView = [[UIImageView alloc]initWithFrame:CGRectMake((ScreenWidth-200)/2, (ScreenHeight-200)/2, 200, 200)];
    [self.view addSubview:self.imageView];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end

你可能感兴趣的:(NSThread)