GCD在滚动tableview上滚动数据

问题描述:

我使用大*调度程序从服务器加载图像,但是当我滚动表格数据(即图像,jumble) - 意味着第一个图像来到其他地方,并且像其他图像一样。GCD在滚动tableview上滚动数据

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

    if (cell == nil) { 
     cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] ; 
     cell.selectionStyle=UITableViewCellSelectionStyleNone; 

    } 

    NSDictionary *item=[responseDictionary objectAtIndex:[indexPath row]]; 


    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0ul); 


    NSString *actionForUser=[item objectForKey:@"action"]; 



    objc_setAssociatedObject(cell, 
          kIndexPathAssociationKey, 
          indexPath, 
          OBJC_ASSOCIATION_RETAIN); 

    dispatch_async(queue, ^{ 

     if([actionForUser isEqualToString:like]) 
     { 
      NSURL *url = [NSURL URLWithString:[item objectForKey:@"user_image"]]; 
      NSData *data1 = [[NSData alloc] initWithContentsOfURL:url]; 
      UIImage *image1 = [[UIImage alloc] initWithData:data1]; 

      //userProfileimage 
      UIButton *userImageButton = [[UIButton alloc] initWithFrame:CGRectMake(10,5, 40,40)]; 
      userImageButton.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter; 
      userImageButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter; 
      [userImageButton setBackgroundImage:image1 forState:UIControlStateNormal]; 
      [userImageButton addTarget:self 
          action:@selector(userImageButtonclick:) 
        forControlEvents:UIControlEventTouchDown]; 
      [cell.contentView addSubview:userImageButton]; 

     } 
    }); 
    return cell; 
} 

这是因为你的异步方法完成的时候,cell已回收并用于不同的索引路径,所以你要更新错误的小区。

在更新的时候,通过使用tableview的(而不是数据源方法)cellForRowAtIndexPath:方法获取单元格引用。这将返回正确的单元格,或者如果单元格不在屏幕上,则返回零。您可以安全地更新此单元格。

您可能应该将图像数据添加到您的模型中,以便您不重复下载它。

作为一个例子,而不是这一行:

[cell.contentView addSubview:userImageButton]; 

你应该有这样的事情:

UITableViewCell *cellToUpdate = [tableView cellForRowAtIndexPath:indexPath]; 
[cellToUpdate.contentView addSubview:userImageButton]; 

有你的代码进一步的问题;你没有缓存图像,每次这个单元格出现在屏幕上时你都会添加这个子视图,如果这个单元格被重用于不需要按钮的情况,那么按钮仍然存在。我只讨论了你的问题中所描述的“GCD j”“。

+0

jrturton因为我是一个新来的人,所以没有得到正是你所说的话可以通过codeing.and thnx解释它的回复 – ashForIos 2013-03-06 08:32:19

+1

添加了一个代码示例 – jrturton 2013-03-06 10:36:50

+0

thnx jrturton我会尝试使用它。 – ashForIos 2013-03-06 13:13:50