0

我在表格视图 cellforRowAtIndexPath 方法中使用 [NSOperationQueue mainQueue] 和 NSInvocationOperation 在后台从 Web 加载图像。但下载图像后它并没有停止。这是我的代码

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell=[mytable dequeueReusableCellWithIdentifier:@"cell"];


    if (cell == nil) 
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];

    }

    imageLabel=(UIImageView *)[cell viewWithTag:5];
    UIImage *image=[dict objectForKey:[appSmallLogos objectAtIndex:indexPath.row]];
    if (image) {
        imageLabel.image=image;
    } else {   
        NSURL *on=[appSmallLogos objectAtIndex:indexPath.row];
        NSString *on1=[appNames objectAtIndex:indexPath.row];


        NSMutableArray *array=[[NSMutableArray alloc] initWithObjects:on,on1,indexPath, nil];
        operation = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(didGetAlbums:) object:arr];

        q =[NSOperationQueue mainQueue];
        [q addOperation:operation];

    imageLabel.image=[dict objectForKey:on1];
    }

    return cell;
}

//didgetalbums method

- (void )didGetAlbums: (NSMutableArray* )url
{

    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH,  0ul);
    dispatch_async(queue, ^{
        NSData *data=[NSData dataWithContentsOfURL:[url objectAtIndex:0]];
        UIImage *image1 = [UIImage imageWithData:data];

        dispatch_sync(dispatch_get_main_queue(), ^{
            [dict setObject:image1 forKey:[url objectAtIndex:1]];

        });
    });

    //reload the requested cell after download image
    [self. mytable beginUpdates];
    [self. mytable reloadRowsAtIndexPaths:[NSArray arrayWithObjects:[url objectAtIndex:2], nil] withRowAnimation:UITableViewRowAnimationNone];
    [self. mytable endUpdates];    // imageLabel.image=[dict objectForKey:[appSmallLogos objectAtIndex:indexPath.row]];
}
4

0 回答 0