ios - UIImage 显示为 nil

标签 ios swift uiimage

我的项目有问题。我是编码新手。我不断收到错误 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/

相关文章:

ios - Localycs iOS 崩溃

ios - 如何在 Swift 中验证 X509Certificate?

ios - 首次登录应用后自动填充iOS12提示信息用户保存密码?

ios - Swift 3 将图像添加到文档并检索

ios - fatal error : Unexpectedly found nil while unwrapping an Optional value NSURL

ios - 更改 UIView 高度和 subview y 位置 [Swift]

ios - 如何使用一个数组作为另一个数组的谓词?

ios - UIButton 未在 swift 中调用操作函数

ios - 如何使用字符串参数创建选择器

objective-c - 无法将 UIImage 项目添加到 NSMutableArray - EXC_BAD_ACCESS 错误