<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>
#import "ViewController.h"
@interface ViewController ()
/*strong:强引用
*weak:弱引用,释放后指向0地址
*assign:释放后指针指向不变,即野指针 */
@property (nonatomic,retain)UIImageView *downIV;
@property (weak,nonatomic)UIScrollView *scrollView;
@end
@implementation ViewController
//重写此方法,默认不会加载Xib&Sb
-(void)loadView{
//下面错误写法,weak,对象将在赋值之后释放,对象为空
// _scrollView = [[UIScrollView alloc]initWithFrame:[UIScreen mainScreen].bounds];
UIScrollView *sc = [[UIScrollViewalloc]initWithFrame:[UIScreenmainScreen].bounds]; //取设备屏幕大小
self.scrollView = sc;
self.view = sc;
UIImageView *imageView = [[UIImageViewalloc]init];
[self.viewaddSubview:imageView];
_downIV = imageView;
}
- (void)viewDidLoad {
[superviewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
[selfdownloadImage];
//创建线程
NSThread *thread = [[NSThreadalloc]initWithTarget:selfselector:@selector(downloadImage)object:nil];
[thread start];
}
//下载图片
-(void)downloadImage{
NSLog(@"downloadImage %@",[NSThreadcurrentThread]);
//休眠
// [NSThread sleepForTimeInterval:2];
_downIV = [[UIImageViewalloc]initWithFrame:self.view.frame];
[self.viewaddSubview:_downIV];
NSString *path =@"http://img.tuku.cn/file_big/201503/55b7341dbe084fa6b995a33f2407c0e0.jpg";
NSURL *url = [NSURLURLWithString:path];
NSData *data = [NSDatadataWithContentsOfURL:url];
UIImage *image = [UIImageimageWithData:data];
//线程间通信 子->主
/*参数1:方法
*参数2:方法的参数
*参数3:等待执行完成 */
[selfperformSelectorOnMainThread:@selector(updateUI:)withObject:imagewaitUntilDone:NO];
}
//更新UI,所有对UI的操作都需要放在主线程里
- (void)updateUI:(UIImage *)image{
NSLog(@"update %@",[NSThreadcurrentThread]);
_downIV.image = image;
//按图片大小显示
[self.downIVsizeToFit];
[_scrollViewsetContentSize:image.size];
}
@end
//GCD 简单写法
- (void)viewDidLoad {
[superviewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
dispatch_async(dispatch_get_global_queue(0,0), ^{
_downIV = [[UIImageViewalloc]initWithFrame:self.view.frame];
[self.viewaddSubview:_downIV];
NSString *path =@"http://img.tuku.cn/file_big/201503/55b7341dbe084fa6b995a33f2407c0e0.jpg";
NSURL *url = [NSURLURLWithString:path];
NSData *data = [NSDatadataWithContentsOfURL:url];
//闭包
UIImage *image = [UIImageimageWithData:data];
//线程间通信
dispatch_async(dispatch_get_main_queue(), ^{
NSLog(@"update %@",[NSThreadcurrentThread]);
//按图片大小显示
self.downIV.image = image;
[self.downIVsizeToFit];
[_scrollViewsetContentSize:image.size];
});
});
}