2

我试图在 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)")
      }
    })
  }
}
4

1 回答 1

6

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

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)")
      }
    })
  }
}
于 2015-03-24T14:42:32.700 回答