您的位置:首页 > 移动开发 > IOS开发

IOS多线程下载图片

2016-04-18 19:35 399 查看
ViewController.h

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController{
UIImageView *imageView;
}

@property(nonatomic, retain) IBOutlet UIImageView *imageView;

@end


上面定义一个imageView

ViewController.m

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController
@synthesize imageView;
- (void)viewDidLoad {
[super viewDidLoad];
NSString *url  = @"http://d.hiphotos.baidu.com/image/w%3D1366%3Bcrop%3D0%2C0%2C1366%2C768/sign=6cbcab9dabec8a13141a53e3c135aaec/aa64034f78f0f7369453c3730855b319ebc41316.jpg" ;

// Do any additional setup after loading the view, typically from a nib.
UIButton *myDemoButton = [[UIButton alloc]initWithFrame:CGRectMake(50, 50, 200, 50)];
[myDemoButton setBackgroundColor:[UIColor purpleColor]];
[myDemoButton addTarget:self action:@selector(myButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:myDemoButton];
//    [self downLoadImage:[NSString stringWithFormat:@"%s", IMAGE_VIEW]];

NSThread *myThread = [[NSThread alloc] initWithTarget:self selector:@selector(downLoadImage:) object:url];
[myThread start];
}
- (void)myButtonPressed:(id)sender{
NSLog(@"myDemoButton pressed");

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

- (void)downLoadImage:(NSString *)url{
NSData *imageData = [[NSData alloc]initWithContentsOfURL:[NSURL URLWithString:url]];
sleep(5);
UIImage *imageImage = [[UIImage alloc] initWithData:imageData];
if(imageImage){
[self performSelectorOnMainThread:@selector(updateUI:) withObject:imageImage waitUntilDone:YES];
}
}

- (void)updateUI:(UIImage *)image{
self.imageView.image = image;

}
@end


点击骚紫色button显示图片

mac电脑不太会操作就不截图了
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: