【问题标题】:retrieve an optional value swift快速检索可选值
【发布时间】:2015-08-05 19:54:17
【问题描述】:

我有这个功能:

func richiamoImmagine()
{
    let avatarFile = PFUser.currentUser()!["Avatar"] as! PFFile
    avatarFile.getDataInBackgroundWithBlock {
        (imageData:NSData?, error:NSError?) -> Void in
        if error == nil {
            if let finalimage = UIImage(data: imageData!) {
                self.avatarImage.image = finalimage
            }
        }
    }
}

从解析中检索图像,但如果用户没有任何图像,则该函数会导致崩溃,并且此错误会出现在日志中:

致命错误:在展开可选值时意外发现 nil

我知道我必须这样写:

if let "variable" == avatarFile 

因此,如果函数没有检索到任何内容,至少它不会使我的应用程序崩溃!我该如何解决这个错误?

【问题讨论】:

  • 只是不要使用感叹号。他们的意思是“我会崩溃!”
  • 但我必须用“?”替换它在下面的行中,我必须输入“!”因为xcode想要它!应用仍然崩溃!
  • 一般来说,使用强制解包操作符! 不会神奇地使可选的not nil。明智地使用它,如果不确定,请避免使用它并尝试使用可选绑定和可选链接
  • "并且在下面的行中我必须输入“!”“不,你没有。你永远必须输入!

标签: image swift parse-platform optional


【解决方案1】:

大概发生崩溃的地方就在这一行:

if let finalimage = UIImage(data: imageData!) {

因为您使用的是强制展开运算符。我会在前面的if 语句中添加一个快速检查来检查不为零:

if error == nil && imageData != nil {

甚至更好地使用可选绑定

if let imageData = imageData where error == nil {
    if let finalimage = UIImage(data: imageData) {
        self.avatarImage.image = finalimage
    }
}

更新:如果错误发生在第一行,那么您应该(再次)使用可选绑定来防止意外崩溃:

if let avatarFile = PFUser.currentUser()?["Avatar"] as? PFFile {

}

【讨论】:

  • Xcode 说错误在第一行: let avatarFile = PFUser.currentUser()!["Avatar"] as! PF文件
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-05-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多