回复按钮导致崩溃

时间:2019-06-17 09:38:48

标签: ios swift xcode

我正在制作4Chanesque答复视图控制器。我的计划是允许用户在textView中写答复。然后,答复按钮应获取其文本并将其添加到Post类中称为“ comment”的字符串数组中。然后tableView将在该帖子的评论部分的底部显示其评论。

这是我的View Controller for Comment:

import Foundation
import UIKit
import Firebase

class MainTextView: UIViewController, UITextViewDelegate {

@IBOutlet weak var titleText: UILabel!
@IBOutlet weak var mainText: UILabel!

@IBOutlet weak var commentPlaceHolder: UILabel!
@IBOutlet weak var newCommentLabel: UITextView!
weak var delegate:NewPostVCDelegate?

@IBAction func reply(_ sender: UIButton) {

// Firebase code here
    let postRef = Database.database().reference().child("posts").childByAutoId()

    let postObject = [
        "comment": newCommentLabel.text,
        "timestamp": [".sv": "timestamp"]
        ] as [String : Any]

    postRef.setValue(postObject, withCompletionBlock: { error, ref in
        if error == nil {
            self.delegate!.didUploadPost(withID: ref.key!)
            self.dismiss(animated: true, completion: nil)
        }  else {
            // Handle error

        }
    })
    newCommentLabel.text = String()
    commentPlaceHolder.isHidden = false
}
var post: Post?

供参考,这是我的Post课

import Foundation

class Post {
var id:String
var title: String
var text:String
var createdAt:Date
var comment: [String] = []

init(id: String, title: String,text:String,  timestamp:Double, comment: [String] = []) {
    self.id = id
    self.title = title
    self.text = text
    self.createdAt = Date(timeIntervalSince1970: timestamp / 1000)




}
static func parse(_ key:String, data:[String:Any]) -> Post? {
    if let title = data["text"] as? String,
        let text = data["title"] as? String,
        let timestamp = data["timestamp"] as? Double {
        return Post(id: key, title: title,  text: text, timestamp:timestamp, comment: [])
        }


    return nil
    }
}

NewPostVCDelegate在我的NewPostViewController中声明为:

protocol NewPostVCDelegate: class {
func didUploadPost(withID id:String)
  }

我想知道当我真的只想在现有帖子中添加评论时,委托人是否正在促使我尝试发表新帖子。我不确定如何以编程方式解决此问题。目前,当我按下回复按钮时,我收到崩溃消息。它显示为:“线程1:致命错误:在展开可选值时意外发现nil”。此错误消息红色突出显示了以下行:“ self.delegate!.didUploadPost(withID:ref.key!)”。谢谢您的帮助。

1 个答案:

答案 0 :(得分:1)

因为坠机在这里

self.delegate!.didUploadPost(withID: ref.key!)

您的代表是nil,您需要在这里destination.delegate = self

进行设置
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { 
    tableView.deselectRow(at: indexPath, animated: true) 
      if let destination = storyboard?.instantiateViewController(withIdentifier:"MainTextView") as? MainTextView {
          destination.post = posts[indexPath.row]  
          destination.delegate = self
          navigationController?.pushViewController(destination, animated: true) 
     }
 }