Sobes.tech
Junior — Middle

Môžeš sa podeliť o príklad technického vylepšenia v projekte a opísať jeho realizáciu?

sobes.tech AI

Odpoveď od AI

V jednom z mojich iOS projektov som zlepšil výkon načítania obrázkov v zozname (UITableView) implementáciou cache a asynchrónneho načítania.

Implementácia:

  • Použil som NSCache na uloženie už načítaných obrázkov, čím som sa vyhol ich opätovnému načítaniu zo siete.
  • V metóde cellForRowAt som kontroloval, či je obrázok v cache; ak áno, zobrazil som ho okamžite.
  • Ak nebol v cache, spustil som asynchrónne načítanie cez URLSession, po načítaní obrázok som uložil do cache a aktualizoval bunku.

Prí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ýrazne znížilo záťaž na sieť a zlepšilo plynulosť rolovania.