Swift:使用带GCD的引用类型

时间:2016-04-19 16:47:33

标签: ios swift grand-central-dispatch

我有这个递归函数,等待加载图像。 但是,它无法正常运行。 UIImageView永远不会更新。

(图像参数是类类型的字段,使用Alamofire下载)

由于UIImage是引用类型,错误是什么?

func waitForImage(image: UIImage?, imageName: String, imageView: UIImageView, waitTimeInSec: Double = 0.5, repeatCount: Int = 0) {
    let maxWaits = 10

    if image != nil {
        imageView.image = image
    }
    else {
        if repeatCount > maxWaits {
            return
        }

        delay(waitTimeInSec) {
            self.waitForImage(image, imageName: imageName, imageView: imageView, 
                      waitTimeInSec: waitTimeInSec, repeatCount: repeatCount + 1)
        }
    }
}

延迟定义为:

func delay(delay:Double, closure:()->()) {
  dispatch_after(
    dispatch_time(
        DISPATCH_TIME_NOW,
        Int64(delay * Double(NSEC_PER_SEC))
    ),
    dispatch_get_main_queue(), closure)
}

以下是我如何调用该函数:

waitForImage(item.owner.picture, imageName: "Owner's Avatar, \(item.owner.ID)", imageView: ivAvatar)

1 个答案:

答案 0 :(得分:0)

我相信你不需要引用图像,而是希望通过制作image和inout参数来引用对图像的引用。所以可能是这样的:

func waitForImage(inout image: UIImage?, imageName: String, imageView: UIImageView, waitTimeInSec: Double = 0.5, repeatCount: Int = 0)

并称之为:

waitForImage(&item.owner.picture, imageName: "Owner's Avatar, \(item.owner.ID)", imageView: ivAvatar)

在考虑了一点之后,另一种方法仍然可以提供您想要的通用解决方案,即创建一个协议,如:

protocol ImageProvider {
    var providedImage: UIImage? { get }
}

然后让item.owner类符合它。然后调整waitForImage

func waitForImage(imageProvider: ImageProvider, imageName: String, imageView: UIImageView, waitTimeInSec: Double = 0.5, repeatCount: Int = 0) {
    let maxWaits = 10

    if imageProvider.providedImage != nil {
        imageView.image = imageProvider.providedImage
    }
    else {
        if repeatCount <= maxWaits {
            delay(waitTimeInSec) {
                self.waitForImage(imageProvider, imageName: imageName, imageView: imageView,
                      waitTimeInSec: waitTimeInSec, repeatCount: repeatCount + 1)
        }
    }
}

并称之为:

waitForImage(item.owner, imageName: "Owner's Avatar, \(item.owner.ID)", imageView: ivAvatar)