Search code examples
iosswiftsdwebimagedidset

Issue with setting didSet


I am getting image from a url using SDWebImage and assigning it to an array like so...

let imgUrl = arrProduct?[indexPath.section].images[indexPath.row].url
let placeholderImage = UIImage(named: "appLogo.jpg")

cell.prdImgView.sd_setImage(with:imgUrl, 
                placeholderImage:placeholderImage,
                         options: []) { (image, error, imageCacheType, imageUrl) in
    arrayOfSelectedImages.append(image!)
}

Now I just don't want to add to an array like this. Instead, after adding the image to arrayOfSelectedImages I want to update this array value in didSet and empty the arrayOfSelectedImages array so that every time the array gets a new value, it updates that value in didSet and & arrayOfSelectedImages is emptied. So finally my array in didSet will have all the images I need and I can pass those images on to some other view...How can I achieve this..?


Solution

  • The task is quite straight-forward to accomplish. You need a valid criteria to compare appended objects and, what's important, criteria you apply before appending object to an array, not after that. Using didSet to verify appended object and delete it if unsuitable, is bad design.

    If your UIImage objects are not encapsulated within any other object or struct to uniquely id these objects and if you don't have an option whether or not particular image should be downloaded at all (which is the best and most proper practice), you can compare two UIImage objects by comparing underlying image data. This could previously be accomplished by obtaining PNG representation of an image and comparing that data, but now there's a good simple method.

    Comparing Images

    The isEqual(:) method is the only reliable way to determine whether two images contain the same image data. The image objects you create may be different from each other, even when you initialize them with the same cached image data. The only way to determine their equality is to use the isEqual(:) method, which compares the actual image data. Listing 1 illustrates the correct and incorrect ways to compare images.

    https://developer.apple.com/documentation/uikit/uiimage

    Usage

    if !arrayOfSelectedImages.contains(where: { $0.isEqual(image) }) {
        arrayOfSelectedImages.append(image)
    }