我的项目有问题。我是编码新手。我不断收到错误 fatal error: expectedly found nil while unwrapping an Optional value (lldb)。变量“image”似乎没有生成图像,而是生成“nil”。变量“photo”生成的名称与我的 JPG 图像名称相对应。对于某些变量“image”无法生成该 UIImage,而是生成 nil。希望你能帮助我。
import UIKit
class Photo {
class func allPhotos() -> [Photo] {
var photos = [Photo]()
if let URL = NSBundle.mainBundle().URLForResource("Photos", withExtension: "plist") {
if let photosFromPlist = NSArray(contentsOfURL: URL) {
for dictionary in photosFromPlist {
let photo = Photo(dictionary: dictionary as! NSDictionary)
photos.append(photo)
}
}
}
return photos
}
var caption: String
var comment: String
var image: UIImage
init(caption: String, comment: String, image: UIImage) {
self.caption = caption
self.comment = comment
self.image = image
}
convenience init(dictionary: NSDictionary) {
let caption = dictionary["Caption"] as? String
let comment = dictionary["Comment"] as? String
let photo = dictionary["Photo"] as? String
let image = UIImage(named: photo!)?.decompressedImage
self.init(caption: caption!, comment: comment!, image: image!)
}
func heightForComment(font: UIFont, width: CGFloat) -> CGFloat {
let rect = NSString(string: comment).boundingRectWithSize(CGSize(width: width, height: CGFloat(MAXFLOAT)), options: .UsesLineFragmentOrigin, attributes: [NSFontAttributeName: font], context: nil)
return ceil(rect.height)
}
}
感觉跟图片的解压有关:
导入 UIKit
扩展 UIImage{
var decompressedImage: UIImage {
UIGraphicsBeginImageContextWithOptions(size, true, 0)
drawAtPoint(CGPointZero)
let decompressedImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return decompressedImage
}
最佳答案
很可能是这两行:
let image = UIImage(named: photo!)?.decompressedImage
self.init(caption: caption!, comment: comment!, image: image!)
第一行为 image
赋值,但特别允许 nil 值。这就是 ?
的含义。此外,在 decompressedImage
(其目的...不清楚)中,允许调用 UIGraphicsGetImageFromCurrentImageContext
返回 nil。
然后在第二行中使用 image!
而不检查它是否为 nil。根据您的崩溃,它是零,这意味着以下情况之一为真:
photo
实际上不包含您的应用程序包中的图像名称,或者photo
有一个有效的名称,但文件已损坏到UIImage
无法处理的程度,或者decompressedImage
返回 nil,因为UIGraphicsGetImageFromCurrentImageContext
出于某种原因。
关于ios - UIImage 显示为 nil,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34324698/