I have the following bit of code:
dispatch_async(dispatch_get_global_queue(0, 0), ^
{
[self loadThumbnails]; //loads an array of photos which get loaded into each table cell
[self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:NO];
});
in the initializer of my subclassed UITableView
. I'd like it for the table to load these thumbnails on a separate thread because they take some time to load. Yet, when I execute the above code, the tableview comes up blank. So my first question is how can I fix this?
My second question is, I'd like for this dispatch queue to be killed once the tableview object is released. Is this possible / how would this be accomplished?
Tried implementing the solution from Vikings and here is what I got:
- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellIdentifier = @"ThumbnailCell";
UITableViewCell *tableViewCell = [self dequeueReusableCellWithIdentifier:cellIdentifier];
if (!tableViewCell)
{
tableViewCell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier] autorelease];
}
NSInteger thumbnailsPerCell = self.thumbnailViewsPerCell;
NSInteger startingThumbnailIndex = indexPath.row * thumbnailsPerCell;
NSInteger totalThumbnails = MIN(((indexPath.row * thumbnailsPerCell) + thumbnailsPerCell) , [self.thumbnailViews count]) - startingThumbnailIndex;
if ([tableViewCell.contentView subviews])
{
for (UIView *subview in [tableViewCell.contentView subviews])
{
[subview removeFromSuperview];
}
}
for (int i = 0; i < totalThumbnails; i++)
{
UIView *thumbnailView = [[UIView alloc] initWithFrame:CGRectMake(i * self.cellDimension, 0, self.cellDimension, self.cellDimension)];
UIView *thumbnail = [[self.thumbnailCache objectForKey:[NSNumber numberWithInt:i]] retain];
if (thumbnail)
{
[thumbnailView addSubview:thumbnail];
[tableViewCell.contentView addSubview:thumbnailView];
[thumbnailView release];
[thumbnail release];
}
else
{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0),
^{
UIView *thumbnail = [[self createThumbnailAtIndex:i] retain];
if (thumbnail)
{
dispatch_async(dispatch_get_main_queue(),
^{
UITableViewCell *tableViewCell = [self cellForRowAtIndexPath:indexPath];
if (tableViewCell)
{
[thumbnailView addSubview:thumbnail];
[tableViewCell.contentView addSubview:thumbnailView];
[thumbnailView release];
[thumbnail release];
}
});
[self.thumbnailCache setObject:thumbnail forKey:[NSNumber numberWithInt:i]];
}
});
}
}
return tableViewCell;
}
This is producing a blank tableView. Any clue as to why?