static NSString *CellIdentifier = @"Cell"; //重用儲存格 JKCallbacksTableViewCell *cell = (JKCallbacksTableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if (cell == nil) { cell = [[[JKCallbacksTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease]; } //獲得要載入的檔案名稱 NSString *imageFilename = [imageArray objectAtIndex:[indexPath row]]; NSString *imagePath = [imageFolder stringByAppendingPathComponent:imageFilename]; //圖片名稱 [[cell textLabel] setText:imageFilename]; [cell setSelectionStyle:UITableViewCellSelectionStyleNone]; // If we already have an image cached for the cell, use that. Otherwise we need to go into the // background and generate it. UIImage *image = [imageCache objectForKey:imageFilename]; if (image) { //圖片緩衝不存在,載入圖片 [[cell imageView] setImage:image]; } else { dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0ul); // Get the height of the cell to pass to the block. CGFloat cellHeight = [tableView rowHeight]; // Now, we can’t cancel a block once it begins, so we’ll use associated objects and compare // index paths to see if we should continue once we have a resized image. // 建立關聯對象 /** * @param cell 來源物件 * @param kIndexPathAssociationKey 關聯key * @param indexPath 關聯的值 * @param OBJC_ASSOCIATION_RETAIN 關聯方式 */ objc_setAssociatedObject(cell, kIndexPathAssociationKey, indexPath, OBJC_ASSOCIATION_RETAIN); /* 使用關聯引用,你可以對一個對象添加資料而不需要修改這個類定義,這在你沒有這個類的原始碼時很有用, 或者是為了二進位相容的原因你無法修改這個對象的時候。 關聯基於一個key,所以你可以在一個對象上添加多個關聯,每個使用不同的key,關聯對象也可以確保被關 聯的對象是否存在,至少在來源物件的生命週期內(也就是說這個對象沒有將被引入到記憶體回收系統的可能性) */ dispatch_async(queue, ^{ //子線程 UIImage *image = [UIImage imageWithContentsOfFile:imagePath]; //調整圖片大小 UIImage *resizedImage = [image resizedImageWithContentMode:UIViewContentModeScaleAspectFill bounds:CGSizeMake(cellHeight, cellHeight) interpolationQuality:kCGInterpolationHigh]; dispatch_async(dispatch_get_main_queue(), ^{ //主線程(非同步作業) //檢索關聯對象 NSIndexPath *cellIndexPath = (NSIndexPath *)objc_getAssociatedObject(cell, kIndexPathAssociationKey); if ([indexPath isEqual:cellIndexPath]) { [[cell imageView] setImage:resizedImage]; } //根據檔案名稱來作為緩衝的key [imageCache setObject:resizedImage forKey:imageFilename]; }); }); }