设置 didSet 的问题

Issue with setting didSet

我正在使用 SDWebImage 从 url 获取图像并将其分配给数组,就像这样...

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

现在我只是不想像这样添加到数组中。相反,将图像添加到 arrayOfSelectedImages 后,我想在 didSet 中更新此数组值并清空 arrayOfSelectedImages 数组,以便每次数组获取新值时,它都会更新该值didSet 并且 & arrayOfSelectedImages 被清空。所以最后我在 didSet 中的数组将包含我需要的所有图像,我可以将这些图像传递给其他视图...我怎样才能实现这一点..?

不完全确定这是否是您想要的,但是 didSet 将在 属性 上触发,如果您修改数组,而不仅仅是在分配数组时,它是一个数组。这是一个例子:

struct A 
{
    var anArray = [1, 2, 3]
    {
        didSet 
        {
            print("Hi, there!")
            anArray.remove(at: 0)
        }
    }
}

var a = A()

a.anArray.append(4)

// Prints Hi there!

print(a.anArray)

// prints [2, 3, 4]

这个任务很容易完成。您需要一个有效的标准来比较附加的对象,重要的是,您在将对象 附加到数组之前而不是之后应用 的标准。使用 didSet 验证附加对象并在不合适的情况下将其删除,是 糟糕的设计

如果您的 UIImage 对象没有封装在任何其他对象或结构中以唯一标识这些对象,并且您没有选择是否应该下载特定图像的选项(这是最佳和最正确的做法),您可以通过比较底层图像数据来比较两个 UIImage 对象。这以前可以通过获取图像的 PNG 表示并比较该数据来完成,但现在有一个很好的简单方法。

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

用法

if !arrayOfSelectedImages.contains(where: { [=10=].isEqual(image) }) {
    arrayOfSelectedImages.append(image)
}