在swift中通过inout参数编写var

时间:2015-01-05 09:54:51

标签: ios swift alamofire

我想将几张图片加载到模型中。我试图用loadImage()函数和inout参数来解决这个问题。但由于某种原因,图像变量总是空的。我没有看到图像。

这里有什么问题?

   public var image: UIImage = UIImage()

   // Somewhere in the init function 
   self.loadImage("http://www.domain.com/cats.img", targetImage: &self.image)

   func loadImage(url:String, inout targetImage:UIImage) {
        dispatch_group_enter(self.dispatch_group);

        println("Start loading image \(url)")

        var request:Alamofire.Request = Alamofire.request(.GET, url).responseImage() {
            (request, _, image, error) in
            if error == nil && image != nil {
                println("imageRequestSuccess")

                // Save the image to the model property
                targetImage = image!

                // Dispatch if success
                dispatch_group_leave(self.dispatch_group)
            } else {
                println("imageRequestFailure")

                // Dispatch also to handle failure
                dispatch_group_leave(self.dispatch_group)
            }
        }
    }

1 个答案:

答案 0 :(得分:0)

使用闭包工作正常...但看起来很难看

self.loadImage(self.image_url!, onSuccess: { s1 in return self.image = s1 })



    func loadImage(url:String, onSuccess: (s1:UIImage) -> () ) {
        dispatch_group_enter(self.dispatch_group);

        println("Start loading image \(url)")

        var request:Alamofire.Request = Alamofire.request(.GET, url).responseImage() {
            (request, _, image, error) in
            if error == nil && image != nil {
                println("imageRequestSuccess")

                onSuccess(s1:image!)

                // Dispatch if success
                dispatch_group_leave(self.dispatch_group)
            } else {
                println("imageRequestFailure")

                // Dispatch also to handle failure
                dispatch_group_leave(self.dispatch_group)
            }
        }
    }