【发布时间】:2019-06-17 18:01:36
【问题描述】:
我正在制作一个 4Chanesque 回复视图控制器。我的计划是允许用户在 textView 中写回复。然后,回复按钮应获取他们的文本并将其添加到 Post 类中名为“comment”的字符串数组中。然后 tableView 将在该帖子的评论部分底部显示他们的评论。
这是我的评论视图控制器:
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?
供参考,这是我的帖子类
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!)”。感谢您的帮助。
【问题讨论】:
-
崩溃的原因以及它指向的位置
-
如果发生崩溃,您可能会在控制台中显示错误消息?哪个是……?另外,您是否指出哪条线路导致了崩溃?我看到一些强制展开(使用“!”),他们是罪魁祸首吗?哪一个?
-
注意:var delegate:NewPostVCDelegate?应该是弱的,否则会导致内存泄漏
-
调试器指向的地方,崩溃发生时哪一行代码上有红色标记
-
在崩溃行下断点,检查调试器窗口看
ref和ref.key或delegate是否有值