图片加载 第三方 KVO

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






  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值