我正在尝试在UIImageView上设置image属性。当我使用UIImage设置.image属性时,它每次都会抛出以下错误:
"在展开可选值时意外发现nil">
问题是我的UIImage不是零。
这是我设置UIImage 的代码
func setPhotosForNewsItem(photoArray:[Photo]) {
println("Image Count: " + String(photoArray.count))
var image:UIImage = photoArray[0].photo
println(image.description)
self.newsImage.image = image
}
这是控制台输出:
图像计数:2UI映像:0x7fdd93c5cdd0,{11151115}致命错误:展开可选值(lldb(时意外发现nil
我可以在xCode中的Quick Look工具上使用我所谓的nil UIImage,并查看我试图使用的照片。当我的UIImage显然不是零时,为什么我会抛出零错误?
更新::
我的数组中似乎没有正确存储UIImage。这里是我下载图像并将它们存储到阵列中以便稍后打开包的地方。
var relatedPhotos:[PFObject] = relations as! [PFObject]
//println(relations!)
var photoArray:[Photo] = [Photo]()
for photo in relatedPhotos {
var newPhoto = Photo()
var photoFile:PFFile = photo.objectForKey("photo") as! PFFile
newPhoto.object = photo
newPhoto.objectID = photo.objectId!
photoFile.getDataInBackgroundWithBlock({(imageData: NSData?, error: NSError?) -> Void in
if (error == nil) {
newPhoto.photo = UIImage(data:imageData!)!
//println(newPhoto.photo)
photoArray.append(newPhoto)
if photoArray.count == relatedPhotos.count {
if newObject is FieldReport {
var report = newObject as! FieldReport
report.photos = photoArray
updatedReports.append(report)
//println("Report Count 1: " + String(updatedReports.count))
}
else {
var report = newObject as! Feature
report.photos = photoArray
updatedReports.append(report)
}
if updatedReports.count == objects.count {
self.delegate?.fieldReports(updatedReports)
}
}
}
})
}
我知道这可以下载和显示照片,因为我刚刚成功地使用了它。对我来说,这意味着我没有正确存储UIImage。有没有其他方法可以存储这些图像文件?
您可以通过安全地打开来防止崩溃的发生
func setPhotosForNewsItem(photoArray:[Photo]) {
println("Image Count: " + String(photoArray.count))
if var image:UIImage = photoArray[0].photo
{
println(image.description)
self.newsImage.image = image
}
}
设置断点并检查的错误
编辑:
我唯一能做的就是检查这里发生了什么:
newPhoto.photo = UIImage(data:imageData!)!
这似乎是所有问题的主要原因。检查imageData的类型,尝试通过例如UIImage(CGImage: <#CGImage!#>)
将其转换为图像。你需要弄清楚如何处理这个图像。