UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

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)
    }

2      

Hacking with Swift is sponsored by RevenueCat.

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

Learn more here

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.