NSThread简单实用

  
#import "ViewController.h"

@interface ViewController ()
@property (weak, nonatomic) IBOutlet UIImageView *imgView;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    NSThread * thread=[[NSThread alloc]initWithTarget:self selector:@selector(run:) object:@"http://img4.duitang.com/uploads/item/201312/22/20131222103125_zLmFL.jpeg"];
    [thread start];
    

}
-(void)run:(NSString* )url{

   NSData*data= [[NSData alloc]initWithContentsOfURL:[NSURL URLWithString:url]];

    UIImage* img=[[UIImage alloc]initWithData:data];
    
    if (img!=nil) {
        //到主线程去更新UI
        [self performSelectorOnMainThread:@selector(update:) withObject:img waitUntilDone:YES];
    }
}

-(void)update:(UIImage*)img{
    [_imgView setImage:img];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end

效果图

NSThread简单实用_第1张图片

你可能感兴趣的:(ios)