您好,我正在使用 NSOperationQueue 在后台下载图像。我创建了一个自定义 NSOperation 来下载图像。我将图像放在表格单元格中。问题是如果我执行 [operationQueue setMaxConcurrentOperationCount: 10] 并向下滚动几个单元格,程序会因 EXC_BAD_ACCESS 而崩溃。每次它在桌子的同一个地方崩溃。一个接一个地有 3 个单元,它们是同一家公司的,并且具有相同的徽标,因此基本上它应该下载图像 3 次。每隔一段时间它工作正常。
- (void) main
{
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
NSURL *url = [[NSURL alloc] initWithString:self.imageURL];
debugLog(@"downloading image: %@", self.imageURL);
//NSError *error = nil;
NSData *data = [[NSData alloc] initWithContentsOfURL:url];
[url release];
UIImage *image = [[UIImage alloc] initWithData:data];
[data release];
if (image)
{
if (image.size.width != ICONWIDTH && image.size.height != ICONHEIGHT)
{
UIImage *resizedImage;
CGSize itemSize = CGSizeMake(ICONWIDTH, ICONHEIGHT);
//!!! UIGraphicsBeginImageContext NOT THREAD SAFE
UIGraphicsBeginImageContext(itemSize);
CGRect imageRect = CGRectMake(0.0, 0.0, itemSize.width, itemSize.height);
[image drawInRect:imageRect];
resizedImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
self.theImage = resizedImage;
}
else
{
self.theImage = image;
}
[image release];
}
[delegate didFinishDownloadingImage: self];
[pool release];
}
这就是我处理下载图像的方式。如果我在上面的函数中注释掉
[delegate didFinishDownloadingImage: self];
它不会崩溃,但它当然没用。
-(void) didFinishDownloadingImage:(ImageDownloadOperation *) imageDownloader
{
[self performSelectorOnMainThread: @selector(handleDidFinishDownloadingImage:) withObject: imageDownloader waitUntilDone: FALSE];
}
-(void) handleDidFinishDownloadingImage:(ImageDownloadOperation *)imageDownloadOperation
{
NSArray *visiblePaths = [self.myTableView indexPathsForVisibleRows];
CompanyImgDownloaderState *stateObject = (CompanyImgDownloaderState *)[imageDownloadOperation stateObject];
if ([visiblePaths containsObject: stateObject.indexPath])
{
//debugLog(@"didFinishDownloadingImage %@ %@", imageDownloader.theImage);
UITableViewCell *cell = [self.myTableView cellForRowAtIndexPath: stateObject.indexPath];
UIImageView *imageView = (UIImageView *)[cell viewWithTag: 1];
if (imageDownloadOperation.theImage)
{
imageView.image = imageDownloadOperation.theImage;
stateObject.company.icon = imageDownloadOperation.theImage;
}
else
{
imageView.image = [(TestWebServiceAppDelegate *)[[UIApplication sharedApplication] delegate] getCylexIcon];
stateObject.company.icon = [(TestWebServiceAppDelegate *)[[UIApplication sharedApplication] delegate] getCylexIcon];
}
}
}