BLACK FRIDAY SALE: Save 50% on all my Swift books and bundles! >>

List Load Image, use .onAppear Or .task(id:) modifier?

Forums > SwiftUI

hello. Each cell in the list contains an image.

The image data is stored as a binary data type in the core data, and you assign the image via UIImage(data:).

The .task(id:) modifier is onAppear + onChange, and we know that it redraws the view whenever the value of the id parameter changes, allowing for asynchronous processing.

Which modifier should I use, task or onAppear, to load the image stored in coredata for each cell of the list?

Using the task modifier seems to create more threads in the CPU Debug navigator when scrolling...

import SwiftUI

struct MainListImageRowView: View {
    @ObservedObject var item: ItemEntity
    @StateObject private var imageHolder = ImageHolder()

    var body: some View {
        MainListImage
            // 1️⃣ use task modifier 👈
            .task(id: item.unwrappedThumbnailImageData) {
               loadImage()
           }

           // 2️⃣ use onAppear + onChange + onDisappear modifier 👈
            .onAppear(perform: loadImage)
            .onChange(of: item.unwrappedThumbnailImageData) { _ in
                loadImage()
            }
            .onDisappear(perform: unloadImage)
    }

    private func loadImage() {
        imageHolder.image = UIImage(data: item.unwrappedThumbnailImageData)
    }

   

Hacking with Swift is sponsored by Guardsquare

SPONSORED AppSweep by Guardsquare helps developers automate the mobile app security testing process with fast, free scans. By using AppSweep’s actionable recommendations, developers can improve the security posture of their apps in accordance with security standards like OWASP.

Learn more

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.