在我的应用程序中,当用户按下 中的其中一个选项卡UITabBar时,加载视图并将其显示给用户需要花费太多时间,因此可能会造成混淆(这是因为我在 中从网络加载图像UITableView)。所以,我决定在所有图像完成加载之前使用多线程来显示视图。
我正在使用这段代码:
- (UITableViewCell *)tableView:(UITableView *)tableView
           cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *CellIdentifier = @"Cell";
    cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[SetsCustomCell alloc] initWithFrame:CGRectZero];
    }
    // getting url
    NSURL* imgUrl = [[NSURL alloc]initWithString:[[mainArray objectAtIndex:
                       indexPath.row]valueForKey:@"imageURL"]];
    //put this url and current cell in the dictionary
    NSDictionary* params = [NSDictionary dictionaryWithObjectsAndKeys:
                    imgUrl,@"localUrl",cell,@"localCell", nil];
   // multithreading time (calling loadImageWithParams method)
    [self performSelectorInBackground:@selector(loadImageWithParams:)
                           withObject:params];
    return cell;
}
-(void)loadImageWithParams:(NSDictionary*)params {
    NSURL* url = [params objectForKey:@"localUrl"];
    cell = [params objectForKey:@"localCell"];
    UIImage* thumb = [UIImage imageWithData:[NSData dataWithContentsOfURL:url]];
    NSDictionary* backParams = [NSDictionary dictionaryWithObjectsAndKeys: 
                   cell,@"localCell",thumb,@"thumb", nil];
    [self performSelectorOnMainThread:@selector(setImage:)
                        withObject:backParams waitUntilDone:YES];
}
-(void)setImage:(NSDictionary*)params{
    cell = [params objectForKey:@"localCell"];
    UIImage* thumb = [params objectForKey:@"thumb"];
    [cell.imageView setImage:thumb];
    cell.imageView.hidden = NO;
    [cell setNeedsLayout];
}
我只有两个单元格,UITableView问题是只有第二个单元格加载它的图像。第一个单元格仍然是空的。但是,如果我滚动UITableView直到第一个单元格不再可见,然后cellForRowAtIndexPath:再次调用,第一个单元格将获取其图像。
我也尝试过使用多线程,NSOperationQueue但GCD结果相同。
似乎我不清楚多线程是如何工作的,但如果有人指出我的错误,我将非常感激。
谢谢!