Sobes.tech
Junior — Middle

Vai vari dalīties ar piemēru par tehnisko uzlabojumu, kas tika veikts projektā, un aprakstīt tā īstenošanu?

sobes.tech AI

Atbilde no AI

Vienā no iOS projektiem es uzlaboju attēlu ielādes veiktspēju sarakstā (UITableView), ieviešot kešatmiņu un asynchrone ielādi.

Realizācija:

  • Izmantoju NSCache, lai saglabātu jau ielādētos attēlus, lai tos atkārtoti neielādētu no tīkla.
  • cellForRowAt metodē pārbaudīju, vai attēls ir kešā — ja ir, uzreiz to rādīju.
  • Ja attēla nav, sāku asinhrono ielādi ar URLSession, pēc ielādes saglabāju attēlu kešā un atjaunoju šūnu.

Koda piemērs:

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
}

Tas ievērojami samazināja tīkla slodzi un uzlaboja skrollēšanas gludumu.