如何异步加载图像?这就是我目前正在做的事情(借用开源代码来加载图像缩略图):
- (UIImage*)thumbnailListView:(ThumbnailListView*)thumbnailListView
imageAtIndex:(NSInteger)index
{
NSURL* url = [NSURL URLWithString:[recommendedArray objectAtIndex:index]] ;
// [[cell grid_image] setImage:[UIImage imageWithData:[NSData dataWithContentsOfURL:url]]];
NSString *docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
BOOL isImageLoaded = YES;
UIImage *bookImage = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/%@", docPath, [[recommendedArray objectAtIndex:index] lastPathComponent]]];
if(bookImage == nil)
isImageLoaded = NO;
if(!isImageLoaded){
UIImage *thumbnailImage =[UIImage imageNamed:@"App-icon-144x144.png"];}
else{
UIImage *thumbnailImage = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",[recommendedArray objectAtIndex:index]]]]];
return thumbnailImage;
}
}
我尝试将以下内容添加到该方法中,但它会为 NSURL 产生错误:
dispatch_queue_t imageLoadQueue = dispatch_queue_create("com.g.load", NULL);
dispatch_async(imageLoadQueue, ^{
//Wait for 5 seconds...
usleep(1000000);
NSArray *docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
for(int k=0; k < [images count];k++){
NSLog(@"Loading %d Image", k);
NSString *imgURL = [images objectAtIndex:k];
NSData *imgData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:imgURL]];
[imgData writeToFile:[NSString stringWithFormat:@"%@/%@", docPath, [imgURL lastPathComponent]] atomically:YES];
}
[[self collectionView] reloadData];
NSLog(@"DONE WITH ALL IMAGES");
});
错误
[NSURL length]: unrecognized selector sent to instance 0x12ea7240
2013-04-18 11:18:35.456 AssamKart[3084:14d03] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[NSURL length]: unrecognized selector sent to instance 0x12ea7240'