使用GCD下载UITableView标题图像

时间:2013-04-19 00:44:29

标签: ios objective-c grand-central-dispatch

我正在使用GCD下载UITableView的标题图像。

当我使用dispatch_async时,图像根本不显示,当我使用dispatch_sync时,它仍然是同步下载。我该如何解决这个问题?

eventDetailsTable = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height) style:UITableViewStyleGrouped];
eventDetailsTable.dataSource = self;
eventDetailsTable.delegate = self;

[self.view addSubview:eventDetailsTable];

NSString *headerImageUrl = [NSString stringWithFormat:@"%@%@", [currentEvent objectForKey:@"baseurl"], [currentEvent objectForKey:@"sessionimage"]];
NSURL *headerImageURL = [NSURL URLWithString:headerImageUrl];

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
    NSData *imageData = [[NSData alloc] initWithContentsOfURL:headerImageURL];
    UIImage *headerImage = [UIImage imageWithData:imageData];
    UIImageView *headerImageView = [[UIImageView alloc] initWithImage:headerImage];
    eventDetailsTable.tableHeaderView = headerImageView;
});

1 个答案:

答案 0 :(得分:0)

更新UI时,必须在主线程上执行此操作。所以这是解决方案:

dispatch_async(global_queue, ^{
    //Do your work

    dispatch_async(dispatch_get_main_queue(), ^{
        //Update UI
    });

});