異步下載數據,您:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
使用2個獨立的UITableViewCell對象,一個以填補文本數據,一個用於它需要在線程這樣的圖像作爲dispatch_async
,從我的項目例如:
if (imageUrl.length > 0)
{
NSString *completeURL = @"";
completeURL = [completeURL stringByAppendingString:kPROFILE_IMAGE_URL];
completeURL = [completeURL stringByAppendingString:@"/2/"];
completeURL = [completeURL stringByAppendingString:imageUrl];
completeURL = [completeURL stringByAppendingString:@".png"];
NSString *fileName = [NSString stringWithFormat:@"%@.png", imageUrl];
NSString* path = GetMediaFolder();
BOOL imageExists = [[NSFileManager defaultManager] fileExistsAtPath:[path stringByAppendingPathComponent:fileName]];
if (imageExists)
{
// NSLog(@"Image exists");
// Update UI
dispatch_async(dispatch_get_main_queue(),^
{
UITableViewCell *updateCell = (id)[tableView cellForRowAtIndexPath:indexPath];
UIImageView *imageView = (UIImageView*)[updateCell viewWithTag:kTAG_IMAGE];
imageView.image=[UIImage imageWithContentsOfFile:[path stringByAppendingPathComponent:fileName]];
imageView.layer.cornerRadius = 23.0;
imageView.layer.borderColor = (__bridge CGColorRef)([UIColor clearColor]);
imageView.layer.borderWidth = 1.0;
imageView.clipsToBounds = YES;
imageView.contentMode = UIViewContentModeScaleAspectFill;
[updateCell setNeedsLayout];
});
}
else
{
// NSLog(@"Image not exists");
// Download The Image
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0),^
{
NSURL *imageURL=[NSURL URLWithString:completeURL];
NSData *image=[NSData dataWithContentsOfURL:imageURL];
[image writeToFile:[path stringByAppendingPathComponent:fileName] atomically:YES];
// Update UI
dispatch_async(dispatch_get_main_queue(),^
{
UITableViewCell *updateCell = (id)[tableView cellForRowAtIndexPath:indexPath];
UIImageView *imageView = (UIImageView*)[updateCell viewWithTag:kTAG_IMAGE];
imageView.image=[UIImage imageWithContentsOfFile:[path stringByAppendingPathComponent:fileName]];
imageView.layer.cornerRadius = 23.0;
imageView.layer.borderColor = (__bridge CGColorRef)([UIColor clearColor]);
imageView.layer.borderWidth = 1.0;
imageView.clipsToBounds = YES;
imageView.contentMode = UIViewContentModeScaleAspectFill;
[updateCell setNeedsLayout];
});
});
}
}
}
return cell;
編輯1:
我看到您不使用圖像,您仍需要異步下載所有數據,並在下載完成時(而不是我的圖像下載,臨時數據和下載的數據)將其填入新的UITableViewCell
。
如果你可以發佈你的tableView實現:cellForRowAtIndexPath:方法...那將是偉大的 –
是來自web服務的數據? –
編輯。是的,它來自web服務。我將數據解析到自定義對象中,然後將它們保存到數組中。 tableview從該數組讀取。 –