我一直在試圖在我的項目上實現一個GCD,它顯示了從XML讀取數據,即使它是我第一次做它我已經成功(可能)實現在nameLabel和detailLabel這兩個都是字符串,但imageLabel(評論的代碼部分)不給任何東西,當我嘗試實現相同的GCD作爲兩個字符串,我不知道發生了什麼,但是當我運行該項目時,它給了一個未知的異常,我想知道如何在代碼的註釋部分實現GCD,以便我能夠在imageView中顯示圖像。在UITableView上實現NSURL的GCD
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *CellIdentifier = @"CustomCell";
dataFileHolder *currentData = [[xmlParser listPopulated] objectAtIndex:indexPath.row];
CustomCellXMLClass *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if(cell == nil) {
cell = [[CustomCellXMLClass alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"CustomCellXMLSample" owner:self options:nil];
cell = [nib objectAtIndex:0];
}
myQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(myQueue, ^{
NSString *nameLabel = [currentData nameOfCat];
NSString *dataToCacheLabel = [myCache objectForKey:nameLabel];
if(nameLabel != nil){
dataToCacheLabel = [NSString stringWithString:nameLabel];
if (dataToCacheLabel != nil) {
[myCache setObject:dataToCacheLabel forKey:nameLabel];
dispatch_async(dispatch_get_main_queue(), ^{
[cell.nameLabel setText:dataToCacheLabel];
});
}
}
NSString *detailLabel = [currentData descriptionOfCat];
NSString *stringToCache = [myCache objectForKey:detailLabel];
if (detailLabel != nil) {
stringToCache = [NSString stringWithString:detailLabel];
if (stringToCache != nil) {
[myCache setObject:stringToCache forKey:detailLabel];
dispatch_async(dispatch_get_main_queue(), ^{
[cell.detailLabel setText:stringToCache];
});
}
}
// NSString *imageURL = [currentData imageLink];
// NSData *dataToCache;
// if (imageURL != nil) {
//
// dataToCache = [NSData dataWithContentsOfURL:[NSURL URLWithString:imageURL]];
// if (dataToCache != nil) {
//
// [myCache setObject:dataToCache forKey:imageURL];
// [cell.imageShow setImage:[UIImage imageWithData:dataToCache]];
//
// }
// else {
//
// NSURL *imageURL = [NSURL URLWithString:@"http://i178.photobucket.com/albums/w255/ace003_album/190579604m.jpg"];
// dataToCache = [NSData dataWithContentsOfURL:imageURL];
// [myCache setObject:dataToCache forKey:imageURL];
// [cell.imageShow setImage:[UIImage imageWithData:dataToCache]];
// }
//
// }
[self.activityIndicator performSelectorOnMainThread:@selector(stopAnimating) withObject:nil waitUntilDone:YES];
});
return cell;
}
如果你想異步檢索圖像,使用'UIImageView'類別,比如[SDWebImage](https://github.com/rs/SDWebImage)或[AFNetworking](https:// github.com/AFNetworking/AFNetworking)。另外,你的實現是使用緩存作爲文本標籤,在這裏我看不到需要。您可能需要緩存「昂貴」的圖片請求,而不是文本標籤的設置。 – Rob