【问题标题】:Writing a var via inout parameter in swift在swift中通过inout参数编写一个var
【发布时间】:2015-01-05 09:54:50
【问题描述】:

我想将几张图片加载到一个模型中。我正在尝试使用 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)
            }
        }
    }

【问题讨论】:

    标签: ios swift alamofire


    【解决方案1】:

    使用闭包效果很好......但看起来很难看

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

    【讨论】:

      猜你喜欢
      • 2021-06-29
      • 1970-01-01
      • 2015-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多