Sobes.tech
Junior — Middle

Pouvez-vous partager un exemple d'amélioration technique apportée au projet et décrire sa mise en œuvre?

sobes.tech IA

Réponse de l'IA

Dans l’un de mes projets iOS, j’ai amélioré la performance du chargement des images dans la liste (UITableView) en implémentant la mise en cache et le chargement asynchrone.

Implémentation :

  • J’ai utilisé NSCache pour stocker les images déjà chargées, évitant ainsi de les recharger depuis le réseau.
  • Dans la méthode cellForRowAt, je vérifiais si l’image était en cache ; si oui, je l’affichais immédiatement.
  • Si l’image n’était pas en cache, je lançais un chargement asynchrone via URLSession, et après le chargement, je stockais l’image en cache et mettais à jour la cellule.

Exemple de code :

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
}

Cela a considérablement réduit la charge sur le réseau et amélioré la fluidité du défilement.