Displaying Photos with PhotoKit inside LazyVGrid uses a lot of memory

I'm trying to implement a Gridview with photos stored in the photos app so the user can choose one picture and pick that as his profile picture. Before SwiftUI I used the collection view and Photos Kit to fetch the images and display them in a grid.

Now that I switched to SwiftUI I tried to use LazyVGrid. I am able to fetch all the photos of the user and display them in a Grid. However it uses a lot of memory. I had a memory leak before but now Instruments isn't showing any leak any more.

I thought it may be, that the Grid isn't really unloading the displayed images, when it gets invisible to the user. However if you scroll up and down multiple times it just uses a lot more memory than before. Like the grid is creating always new views and the old ones don't get deleted. Am I using something wrong or misunderstand the principles of LazyVGrid?

Unrelated to the question, but have you considered switching to PHPickerViewController with UIViewControllerRepresentable instead of building your own picker? (https://developer.apple.com/documentation/photokit/phpickerviewcontroller)

I have, however that would make it one more step for the user. Because I want to have a grid view and on top of that is a square where the user can move and zoom the selected photo from the grid within the same view. (This part is missing in above code)

Have you thought of processing thumbnails from Photohkit instead of making thumbnails from the original image size without actually resizing the original image source data? https://developer.apple.com/documentation/photokit/loading_and_caching_assets_and_thumbnails

Yes, I actually have used that you can see I still have a function called preCacheImages unless I did do something wrong, it doesn't change the memory usage... Additionally I don't know a way to see which rows are "coming up"... or should I just load all photos at once (that doesn't seem like the correct way of doing it.)

Displaying Photos with PhotoKit inside LazyVGrid uses a lot of memory
 
 
Q