1. 用session:
- (void)setImageAction:(id)sender {
self.imV.image = [UIImage imageWithData:sender];
}
- (IBAction)image:(id)sender {
// 设置url
NSURL *url = [NSURL URLWithString:@"http://v.juhe.cn/movie/picurl?2583078"];
// 请求对象
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
NSURLSession *session = [NSURLSession sharedSession];
// 建立连接 请求数据
NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
NSLog(@"%@", data);
// 给imV赋值
// 这样赋值 会等好久 图片才会刷出来 这个是多线程里的子线程,
self.imV.image = [UIImage imageWithData:data];
// 所有UI的刷新必须在主线程操作
// 将加载图片放到主线程
[self performSelectorOnMainThread:@selector(setImageAction:) withObject:data waitUntilDone:YES];
}];
[task resume];
}
2. imageDownLoader:
#pragma mark 使用imageDownLoader下载图片
- (IBAction)imageDownloader:(id)sender {
ImageDownloader *imageDl = [[ImageDownloader alloc] initWithImageUrl:@"http://v.juhe.cn/movie/picurl?2583078" delegate:self];
[imageDl startDownload];
}
- (void)imageDownloader:(ImageDownloader *)downloader didFinishedLoading:(UIImage *)downloadImage {
self.imV.image = downloadImage;
}
3. KVO:
键值观察者:Key-Value-Observer
-(void)dealloc {
// 一定要移除观察者 移除 移除 移除
[self removeObserver:self forKeyPath:@"name"];
[self removeObserver:self forKeyPath:@"per.age"];
}
- (void)viewDidLoad {
[super viewDidLoad];
// 添加观察者
[self addObserver:self forKeyPath:@"name" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:@"shit"];
[self addObserver:self forKeyPath:@"per.age" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:nil];
}
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
self.name = @"haha";
self.per = [[Person alloc] init];
self.per.age = @"hehe da";
}
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context {
// NSLog(@" keyPath = %@ obj = %@ change = %@ con = %@", keyPath, object, change, context);
if ([keyPath isEqualToString:@"name"]) {
self.view.backgroundColor = [UIColor redColor];
}else
self.view.backgroundColor = [UIColor blueColor];
}