Junior — Middle
Kas saaksid jagada tehnilise täiustamise näidet, mis projekti raames tehti, ning kirjeldada selle rakendamist?
sobes.tech AI
Vastus AI-lt
Ühes iOS projektis par uzlabojis 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. cellForRowAtmetodē 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.