今天写了一个demo,从服务器获取图片,而后显示在cell上,你们都知道cell的重用机制,当往下拉的时候,上面的cell遮住了,下面的cell就会重用被遮住的cell,缓存
贴代码:服务器
NSString *urlstring=[dict objectForKey:@"imagePath"]; NSURL *url=[NSURL URLWithString:urlstring];//获取图片的url路径 NSURLRequest *urlrequest=[[NSURLRequest alloc]initWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData timeoutInterval:10]; NSLog(@"UI Thread is %@",[NSThread currentThread]);//这里是主线程 //使用UIImageView+AFNetWorking 异步下载图片,缓存到本地 dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{ NSLog(@"current Thread :%@",[NSThread currentThread]);//这里使用异步机制,确定是非UI线程 [cell.myImage setImageWithURLRequest:urlrequest placeholderImage:[UIImage imageNamed:[dict objectForKey:@"imageName"]] success:^(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image) { NSLog(@"load image thread is %@",[NSThread currentThread]);//猜猜这里是什么线程?? dispatch_async(dispatch_get_main_queue(), ^{ cell.myImage.image=image; NSLog(@"image thread :%@",[NSThread currentThread]);//这里确定是主线程 }); NSLog(@"下载图片成功"); } failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error) { NSLog(@"图片加载失败:%@",error); }];
刚学AFNetworking 的时候,不知道看了谁的博文,说异步
setImageWithURLRequest:urlrequest 这个方法是异步机制,好吧,我认可当时单纯了,直到今天我写这个demo的时候,发现若是不是用异步机制,下载的图片很是慢,有时候还会超时,滑动cell的时候会很是卡,而后我就打印线程,看看是否是在主线程下载东西了,打印结果:

看,
setImageWithURLRequest:urlrequest 这个方法中打印的线程居然是主线程,反正我惊讶了!!