使用解析时遇到nil可选的问题

时间:2016-04-14 06:24:03

标签: swift parsing optional

我试图从Parse下载文件,但我遇到致命错误:崩溃,似乎消息变量为零。我已经尝试过排除故障,而且我知道有一个很容易错过的我只是没有看到。希望社区可以提供帮助,因为我是新手。

class InboxViewController: UITableViewController {

  var messages: [PFObject] = []
  var selectedMessage: PFObject?
  var moviePlayer: MPMoviePlayerController?

   override func viewDidLoad() {
    super.viewDidLoad()
    self.moviePlayer = MPMoviePlayerController()

    let currentUser = PFUser.currentUser()
    if currentUser != nil {
        // Do stuff with the user
        print("Current user: \(currentUser!.username)")
     } else {
  }
}

 override func viewWillAppear(animated: Bool) {
    super.viewWillAppear(animated)

    let query = PFQuery(className: "Messages")
query.whereKey("recipientIds", equalTo: PFUser.currentUser()!.objectId!)
    query.findObjectsInBackgroundWithBlock {
        (objects : [PFObject]?, error: NSError?) -> Void in

        if error == nil {
          for object in objects! {
             let messages = object["file"] as! PFFile
                self.tableView.reloadData()
        print("Retreived \(self.messages.count) messages")
    }
  }
}


}

崩溃断点位于查询的开头。 谢谢社区,另一组经验丰富的眼睛总是有帮助。

1 个答案:

答案 0 :(得分:0)

如果让let

,你可以安全地打开对象
 if let objects  = objects {
   for object in objects 
      let messages = object["file"] as? PFFile
       print(messages) 
       // or you can also safely unwarp here 
       // if let messages = object["file"] as? PFFile {
      // print(message)
      // }
      self.tableView.reloadData()
      print("Retreived \(self.messages.count) messages")
}
}