图片加载 第三方 KVO
发布日期:2022-02-08 18:03:25 浏览次数:44 分类:技术文章

本文共 2354 字,大约阅读时间需要 7 分钟。

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
*)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
*)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]; }

转载地址:https://blog.csdn.net/Evelynzn/article/details/49658063 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:网络部分(iOS)
下一篇:数据库

发表评论

最新留言

第一次来,支持一个
[***.219.124.196]2024年04月07日 08时17分37秒