2013-04-19 46 views
0

我正在使用GCD下載UITableView的標題圖像。使用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; 
}); 

回答

0

當您更新UI時,您必須在主線程上執行此操作。所以這裏是解決方案:

dispatch_async(global_queue, ^{ 
    //Do your work 

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

}); 
+0

我試過了。它可以在模擬器中工作,但只有50%的時間在設備上運行 –