Sobes.tech
Junior — Middle

Můžeš sdílet příklad technického vylepšení provedeného v projektu a popsat jeho realizaci?

sobes.tech AI

Odpověď od AI

V jednom z mých iOS projektů jsem zlepšil výkon načítání obrázků v seznamu (UITableView) implementací cache a asynchronního načítání.

Implementace:

  • Použil jsem NSCache pro ukládání již načtených obrázků, čímž jsem se vyhnul jejich opětovnému načítání ze sítě.
  • V metodě cellForRowAt jsem kontroloval, zda je obrázek v cache; pokud ano, ihned jsem ho zobrazil.
  • Pokud obrázek v cache nebyl, spustil jsem asynchronní načítání přes URLSession, po načtení obrázek uložil do cache a aktualizoval buňku.

Příklad kódu:

let imageCache = NSCache<NSString, UIImage>()

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
    let urlString = imageURLs[indexPath.row]

    if let cachedImage = imageCache.object(forKey: urlString as NSString) {
        cell.imageView?.image = cachedImage
    } else {
        cell.imageView?.image = nil
        DispatchQueue.global().async {
            if let url = URL(string: urlString),
               let data = try? Data(contentsOf: url),
               let image = UIImage(data: data) {
                self.imageCache.setObject(image, forKey: urlString as NSString)
                DispatchQueue.main.async {
                    if let updateCell = tableView.cellForRow(at: indexPath) {
                        updateCell.imageView?.image = image
                        updateCell.setNeedsLayout()
                    }
                }
            }
        }
    }
    return cell
}

Toto výrazně snížilo zatížení sítě a zlepšilo plynulost posouvání.