В вашем .m включите целевое время выполнения c:
#import <objc/runtime.h>
В верхней части раздела @implementation определите статическую константу для использования ниже:
static char * const myIndexPathAssociationKey = "";
В вашем cellForRowAtIndexPath добавьте следующий код:
// Store a reference to the current cell that will enable the image to be associated with the correct
// cell, when the image subsequently loaded asynchronously. Without this, the image may be mis-applied
// to a cell that has been dequeued and reused for other content, during rapid scrolling.
objc_setAssociatedObject(cell,
myIndexPathAssociationKey,
indexPath,
OBJC_ASSOCIATION_RETAIN);
// Load the image on a high priority background queue using Grand Central Dispatch.
// Can change priority by replacing HIGH with DEFAULT or LOW if desired.
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0);
dispatch_async(queue, ^{
UIImage *image = ... // Obtain your image here.
// Code to actually update the cell once the image is obtained must be run on the main queue.
dispatch_async(dispatch_get_main_queue(), ^{
NSIndexPath *cellIndexPath = (NSIndexPath *)objc_getAssociatedObject(cell, myIndexPathAssociationKey);
if ([indexPath isEqual:cellIndexPath]) {
// Only set cell image if the cell currently being displayed is the one that actually required this image.
// Prevents reused cells from receiving images back from rendering that were requested for that cell in a previous life.
[cell setImage:image];
}
});
}];
Наконец, для поддержки наилучшей производительности при быстрой прокрутке на старых устройствах, вы можете сначала загрузить самые последние запрошенные изображения ... для этого см. этот поток для асинхронной загрузки изображений ячеек с использованием последнего в порядке первого вне стека и GCD .