UITableView lags when displaying Swift images

I have tableViewone that shows images in cells, and I get data in a functionviewDidLoad

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
                let cell = tableview.dequeueReusableCellWithIdentifier("cardSelectionCell", forIndexPath: indexPath) as! MyCell
                let card = fetchedResultsController.objectAtIndexPath(indexPath) as! Card
                cell.Name?.text = card.name
                var image: NSData = card.photo as NSData
                cell.logo.image = UIImage(data: image)
                let date = NSDate()
                let formatter = NSDateFormatter()
                formatter.timeStyle = .MediumStyle
                cell.policyExpiryDate.text = formatter.stringFromDate(date)
                return cell 
        }

But the problem is that when I start scrolling, it is tableViewvery lagging so I tried to create a dictionary to convert images to viewDidLoad()

var imageDictionary = [Card:UIImage]()


AllCards = context.executeFetchRequest(request, error: nil) as! [Card]
        for card in AllCards {
            imageDictionary[card] = UIImage(data: card.photo as NSData)
        }

and in function tableView:

cell.logo.image = imageDictionary[card]

but he is still behind

one more question: if one map is added to the main data, I need to get an array of images again, so I tried to create an array in viewDidAppear(), but the images do not appear in the first boot file, and the tableView is still lagging.

+4
source share
2

, :

var image: NSData = card.photo as NSData
cell.logo.image = UIImage(data: image)

. , :

let time1 = CACurrentMediaTime()
var image: NSData = card.photo as NSData
cell.logo.image = UIImage(data: image)
print(CACurrentMediaTime() - time1)

(, 8 ), . , , UIImage - , cellForIndexPath:. - AsyncKit - assync, . , , .

UPD: , , , UIImage. UIImage, URL- , , UIImage , .

shoul , :

cell.logo.image = UIImage(data: image)

, , UIWebView. , , :

autoreleasepool { () -> () in
    cell.logo.image = UIImage(data: image)
}
+5

, , dispatch_async. , , .

    let priority = DISPATCH_QUEUE_PRIORITY_HIGH

    dispatch_async(dispatch_get_global_queue(priority, 0)) {
        if let imgData = card.photo as? NSData {
            let image = UIImage(data: imageData)
            dispatch_async(dispatch_get_main_queue(), { () -> Void in
                cell.logo.image = image
            })
        }
    }
+3

Source: https://habr.com/ru/post/1616498/


All Articles