當我點擊IBAction按鈕時,我得到錯誤「致命錯誤:意外地發現零,而解包可選值」線程1:EXC_BAD_Instruction。意外地發現零,同時展開可選值(Swift,解析)
崩潰發生在Downloader.sharedDownloader.upClicked(postObject)行上。
我研究過這個錯誤,它看起來像postObject變量爲零,導致崩潰。我已閱讀可選項並嘗試使用if let語句和!= nil語句,但這些建議都無法解決問題。
我不明白爲什麼postObject可變回報我TableViewCell爲零,但不是在我的CommentingViewController文件
爲什麼我postObject在我TableViewCell文件返回nil,我會如何解決這個問題?
class TableViewCell: UITableViewCell {
var number:Int = 0
var postObject: PFObject!
@IBOutlet weak var topButton: UIButton!
@IBOutlet weak var postText: UILabel!
@IBOutlet weak var counts: UILabel!
@IBAction func upvote(sender: UIButton) {
number += 1
counts?.text = "\(number)"
Downloader.sharedDownloader.upClicked(counts.text!,post: postObject)
print("success")
}
這裏是相同類型的postObject變量用於就行Downloader.sharedDownloader.postingAComment文件(wf_commentingTextView.text,交:postObject)但不會導致崩潰。
class CommentingViewController: UIViewController {
var postObject:PFObject!
weak var delegate: CommentingViewControllerDelegate?
@IBOutlet weak var wf_commentingTextView: UITextView!
override func viewDidLoad() {
super.viewDidLoad()
NSNotificationCenter.defaultCenter().addObserver(self, selector: "handlePostingComment:", name: postCommentNotification, object: nil)
let item = UIBarButtonItem(title: "Post", style: .Done, target: self, action: "postComment")
navigationItem.rightBarButtonItem = item
}
// post a comment
func postComment(){
if wf_commentingTextView.text.characters.count > 0{
Downloader.sharedDownloader.postingAComment(wf_commentingTextView.text, post: postObject)
}
}
func handlePostingComment(notification: NSNotification){
if let success = notification.object as? Bool{
if success {
delegate?.reloadComments()
} else{
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
這裏是下載器文件,我聲明瞭兩個被比較的函數。
func postingAComment(text:String, post: PFObject){
let comment = PFObject(className: "Comments")
comment.setValue(post, forKey:"post")
comment.setValue(text, forKey:"text")
comment.setValue(PFUser.currentUser(), forKey: "fromUser")
comment.saveInBackgroundWithBlock { (success, error) -> Void in
dispatch_async(dispatch_get_main_queue(), {() -> Void in
NSNotificationCenter.defaultCenter().postNotificationName(postCommentNotification, object: success)
})
}
}
func upClicked(text:String,post: PFObject){
let upVoteObj = PFObject(className: "Upvote")
upVoteObj.setValue(post, forKey: "post")
upVoteObj.setValue(text, forKey: "text")
upVoteObj.setValue(PFUser.currentUser(), forKey: "fromUser")
upVoteObj.saveInBackgroundWithBlock { (success, error) -> Void in
dispatch_async(dispatch_get_main_queue(), {() -> Void in
NSNotificationCenter.defaultCenter().postNotificationName(upVoteNotification, object: success)
})
}
print("vote was saved")
}
謝謝你的幫助。
你在哪裏初始化TableViewCell中的postObject? – beyowulf