尝试使用Swift从解析加载图像时出现致命错误

时间:2015-06-18 13:44:15

标签: ios swift parse-platform

我收到致命错误:在解开可选值时意外地发现了nil。代码从此代码到self.imageArray.append(image!)后出现此错误:

func retrieveImages()
    {
        var query = PFQuery(className: "Maps")
        query.findObjectsInBackgroundWithBlock {
            (objects: [AnyObject]?, error: NSError?) -> Void in
            if error == nil && objects != nil {
                let objects = objects as! [PFObject]
                for object in objects {
                    let imageFile = object["imageFile"] as! PFFile
                    imageFile.getDataInBackgroundWithBlock {
                        (imageData: NSData?, error: NSError?) -> Void in
                        if error == nil {
                            if imageData != nil {
                                let imageData:NSData! = imageData
                                let image = UIImage(data: imageData)
                                self.imageArray.append(image!)
                            }
                        }
                    }
                }
            }
        }
    }

我已检查过每一行代码,并且在我尝试将其附加到imageArray的末尾之前,图像不会变为零。

1 个答案:

答案 0 :(得分:0)

像前面提到的那样,你正在重新分配很多变量。尝试使用if-let语句对可选变量进行如下操作:

func retrieveImages(){
var query = PFQuery(className: "Maps")
query.findObjectsInBackgroundWithBlock { (objects: [AnyObject]?, error: NSError?) in
    if let objects = objects as? [PFObject] where error == nil {
        for object in objects {
            if let imageFile = object["imageFile"] as? PFFile {
                imageFile.getDataInBackgroundWithBlock { (imageData: NSData?, error: NSError?) in
                    if let imageData = imageData, let image = UIImage(data: imageData) {
                        self.imageArray.append(image)
                    }
                }
            }
        }
    }
}

}