当我点击IBAction按钮时,我收到错误"致命错误:在解开可选值时意外发现nil"线程1:EXC_BAD_Instruction。
崩溃发生在 Downloader.sharedDownloader.upClicked(postObject)行。
我已经研究过这个错误,似乎postObject变量是nil并导致崩溃。我已阅读有关选项并尝试使用if let语句和!= nil语句,但这些建议都没有解决问题。
我不明白为什么postObject变量在我的TableViewCell中返回nil但不在我的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")
}
这是在 Downloader.sharedDownloader.postingAComment(wf_commentingTextView.text,post:postObject)行上使用相同类型的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.
}
}
这是Downloader文件,我在其中声明了要比较的两个函数。
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")
}
感谢您的帮助。
答案 0 :(得分:0)
更改此行:
var postObject: PFObject!
要
var postObject = PFObject(className:"PostObject") //Or whatever you class is
会让它停止崩溃,但你可能想要传递postObject,你要么传递nil,要么没有在你的cellForRowAtIndexPath中设置cell.postObject。