UITableView动态加载图片
iPhone在加载列表时,如果每个等待把所有列表中的数据都加载完在显示相关内容,如果列表中有一些比较大的图片,加载的时间比较长,那么给用户的效果就很差了,下面详细是一种实现动态加载图片的办法:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:@"tag"]; if (cell==nil) { cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"tag"] autorelease]; } NSDictionary* one = [array objectAtIndex:indexPath.row]; cell.textLabel.text = [one objectForKey:@"title"];
//延时0.01s后开辟线程 [self performSelector:@selector(delayToDetachNewThread:) withObject:indexPath afterDelay:0.01]; return cell; }
- (void)delayToDetachNewThread:(NSIndexPath *)indexPath
{
[NSThread detachNewThreadSelector:@selector(updateImageForCellAtIndexPath:) toTarget:self withObject:indexPath];
}
- (void)updateImageForCellAtIndexPath:(NSIndexPath *)indexPath { NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
id path = [[array objectAtIndex:indexPath.row] objectForKey:@"image"]; NSURL *url = [NSURL URLWithString:path]; NSData *data = [NSData dataWithContentsOfURL:url]; UIImage *image = [[UIImage alloc] initWithData:data cache:NO];
UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
//主线程中刷新UI [cell.imageView performSelectorOnMainThread:@selector(setImage:) withObject:image waitUntilDone:NO]; [image release]; [pool release]; }
GCD动态加载
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSData *data = [NSDatadataWithContentsOfURL:[NSURLURLWithString:imgPath]];
UIImage *image = [UIImage imageWithData:data];
dispatch_async(dispatch_get_main_queue(), ^{
cell.imageView.image = image;
});
});