尝试检查 PFFile 是否有数据

Attempting to check if PFFile has data or not

我试图在 PFFile 尝试从背景中拉出图像之前检查它是否有数据。我正在尝试这样做,因为如果您尝试打开其中一个对象并且没有图像,我会不断发生致命崩溃!我的问题是我无法让数据检查工作。 PFFile != nil 不起作用,您无法使用 if (recipeImageData) 检查它是否存在,因为 PFFile 不符合布尔协议。如有任何帮助,我们将不胜感激!

这里是变量的声明:

var recipeImageData: PFFile = PFFile()

这里是获取数据的函数:

override func viewWillAppear(animated: Bool) {
  navItem.title = recipeObject["Name"] as? String
  recipeImageData = recipeObject["Image"] as PFFile //Fatally crashes on this line
  // Fetch the image from the background
  if (recipeImageData) {
    recipeImageData.getDataInBackgroundWithBlock({
      (imageData: NSData!, error: NSError!) -> Void in
      if error == nil {
        self.recipeImage.image = UIImage(data: imageData)?
      } else {
        println("Error: \(error.description)")
      }
    })
  }
}

编辑:

我刚刚尝试了这个,发现我可能在错误的区域进行了检查。这是我更新的代码。

override func viewWillAppear(animated: Bool) {
  navItem.title = recipeObject["Name"] as? String
  if let recipeImageData = recipeObject["Image"] as? PFFile {
    // Fetch the image in the background
    recipeImageData.getDataInBackgroundWithBlock({
      (imageData: NSData!, error: NSError!) -> Void in
      if error == nil {
        self.recipeImage.image = UIImage(data: imageData)?
      } else {
        println("Error: \(error.description)")
      }
    })
  }
}

这项检查实际上工作得很好,还有另一个问题导致了崩溃。正确的代码贴在下面:

override func viewWillAppear(animated: Bool) {
  navItem.title = recipeObject["Name"] as? String
  if let recipeImageData = recipeObject["Image"] as? PFFile {
    // Fetch the image in the background
    recipeImageData.getDataInBackgroundWithBlock({
      (imageData: NSData!, error: NSError!) -> Void in
      if error == nil {
        self.recipeImage.image = UIImage(data: imageData)?
      } else {
        println("Error: \(error.description)")
      }
    })
  }
}