GCDで画像をダウンロードする機能を備えたImageDownloaderクラスがあります:
- (void) downloadImageFromURL:(NSURL *) url completionBlock:(void (^)(UIImage *image, NSError *error)) block {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0ul), ^{
NSData *imageData = [NSData dataWithContentsOfURL:url];
UIImage *picture=[UIImage imageWithData:imageData];
if(picture) {
block(picture, nil);
}
else {
NSError *error = [NSError errorWithDomain:@"image_download_error" code:1
userInfo:[NSDictionary dictionaryWithObject:@"Can't fetch data" forKey:NSLocalizedDescriptionKey]];
block(nil, error);
}
});
}
私のtableviewcell(独自のnibファイルで定義)は、次のようにすべての行に対してこの関数を呼び出します:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
//custom cell in nib file
static NSString *MyIdentifier = @"contactsCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier];
if (cell == nil) {
[[NSBundle mainBundle] loadNibNamed:@"contactsCell" owner:self options:nil]; //feedCell je ime nib fajla
cell = contactsCell;
self.contactsCell = nil;
}
if (indexPath.section == 0) {
UIImageView *avatar=(UIImageView *) [cell viewWithTag:1];
avatar.image=[UIImage imageNamed:@"petek.jpg"];
UILabel *nameLabel= (UILabel *) [cell viewWithTag:2];
nameLabel.text=@"Some guy";
UIButton *askBtn=(UIButton *) [cell viewWithTag:3];
[askBtn setTitle:@"Ask" forState:UIControlStateNormal];
[askBtn addTarget:self action:@selector(checkButtonTapped:event:) forControlEvents:UIControlEventTouchUpInside];
}
else {
UIImageView *avatar=(UIImageView *) [cell viewWithTag:1];
ImageDownloader *idl=[[ImageDownloader alloc] init];
NSURL *imageUrl=[NSURL URLWithString:@"http://someImageUrl"];
[idl downloadImageFromURL:imageUrl completionBlock:^(UIImage *image, NSError *error)
{
if(!error) {
dispatch_sync(dispatch_get_main_queue(), ^(void) {
avatar.image=image;
});
} else {
NSLog(@"error %@", error);
}
}];
UILabel *nameLabel= (UILabel *) [cell viewWithTag:2];
nameLabel.text=@"John Stockton";
UIButton *followBtn=(UIButton *) [cell viewWithTag:3];
[followBtn setTitle:@"Follow" forState:UIControlStateNormal];
[followBtn addTarget:self action:@selector(checkButtonTapped:event:) forControlEvents:UIControlEventTouchUpInside];
}
return cell;
}
セクション 1 の画像は正しく読み込まれますが、スクロールすると、セクション 1 の行にセクション 0 の画像が一瞬だけ表示されることがあります。
私は何を間違っていますか?