问题描述:自定义UIImageView,在ImageView中添加了方法:
`-(void)setImageFromURL:(NSURL *)url defaultImage:(UIImage *)defaultImage queue:(NSOperationQueue *)queue;`
方法中使用自定义的ImageLoadOperation操作异步加载图片
`ImageLoadOperation *op=[[ImageLoadOperation alloc] init]; op.url=url; __weak ImageLoadOperation *weakOp = op; op.completionBlock=^{ if (!weakOp.isCancelled) { CIVImageCache *cache=weakOp.resultCache; self.image=[UIImage imageWithData:cache.imageData]; NSData *cacheData=[NSData dataWithContentsOfFile:kCIVCache]; if (cacheData==nil) { cacheData=[[NSData alloc] init]; } NSMutableDictionary *dic=[NSKeyedUnarchiver unarchiveObjectWithData:cacheData]; if (dic==nil) { dic=[[NSMutableDictionary alloc] init]; } if (cache.imageData==nil) { cache.imageData=UIImageJPEGRepresentation([UIImage imageNamed:@"nopic.png"], 1.0); } if (![[dic allKeys] containsObject:cache.url.description]) { [dic setObject:cache.imageData forKey:cache.url.description]; NSData *data=[NSKeyedArchiver archivedDataWithRootObject:dic]; [data writeToFile:kCIVCache atomically:YES]; } } }; queue.maxConcurrentOperationCount = countOfCores(); [queue addOperation:op];`
遇到的问题是这样子加载的图片在Cell中不能立刻显示,需要等很久之后才能显示,不知道为什么。之后又加了一下代码:
[[NSOperationQueue mainQueue] addOperationWithBlock:^{ [self stopActivityView]; [UIView transitionWithView:self.superview duration:1 options:UIViewAnimationOptionTransitionCrossDissolve | UIViewAnimationOptionAllowUserInteraction animations:^{ self.image=[UIImage imageWithData:cache.imageData]; } completion:nil]; }];
使设置图片在主线程中进行,但是这样碰到的问题是在拖动的时候(主要是新的一行显示的时候)会出现明显的卡顿。这时什么坑爹的问题……求大神解答。
两种方法 1:使用tableView复用 2:在线程里面调整图片,主线程setImage
基本找到了问题:是因为读写文件的缘故。我看了SDWebImge的异步加载图片,他的异步能够平滑的拖动不会有卡顿,研究了他的代码发现他使用了NSCache,读缓存的时候只有第一次内存中没有的情况下才会去读取文件,之后都是从内存中获取,我用了NSCache就没有卡顿的现象了,去掉就又有了!不过还是得找找为什么读取文件会造成卡顿。