Search code examples
iosarraysswiftuiimagetvos

Image Array Causing memory Issue


Currently creating an basic image slideshow application, To do this i have created an UIImage array and calling them with the following code.

let imageNames = (0...50).map
    {
        "\($0).JPG"
    }
    let image = UIImage(named: imageNames[0])

    imageView.animationImages = image

    imageView.animationDuration = 50
    imageView.startAnimating()

Was wondering if anyone would be able to offer some advice.


Solution

  • The issue isn't how much memory the image takes on disk, it's about the memory required to address all the pixels on your screen. You don't really need to store the images before you use them. One image of less than 1MB will load very quickly.

    Instead you just need to keep a path to the image, and only when you get to the code that displays the image, then you load it, and display it.

    So, combining Alexander's and KKRocks on-point answers:

    In the top of your class, define your array of filenames:

    let imageNames = (0...55).map { "\($0).JPG" }
    

    Where you are displaying your image:

    if let image = UIImage(named: images[0]) {
       ... the code that is blowing up ...
    }
    

    If you are not sure how to save a file and retrieve it, please see this answer I recently gave on that subject:

    Saving and Retrieving Files in User's Space.