我需要一些认真的帮助。我正在尝试在Firebase的帮助下在我的Xcode项目中创建一个数据库,但是在构建成功之后我一直得到同样的错误然后关闭给我这个错误:
线程1 exc_bad_instruction(code = exc_i386_invop subcode = 0x0)
知道这是关于什么的吗?
这是错误所在的代码行。
let label2 = cell.viewWithTag(2)as! UILabel
这是所有代码
//
// Database.swift
// intern
//
// Created by Lani Daniels on 8/20/17.
// Copyright © 2017 Lani Daniels. All rights reserved.
//
import UIKit
import Firebase
import FirebaseDatabase
struct PostStruct {
let title: String
let message: String
}
class DatabaseViewController: UITableViewController {
var posts: [PostStruct] = []
override func viewDidLoad() {
super.viewDidLoad()
//
let databaseRef = Database.database().reference()
databaseRef.child("Posts").queryOrderedByKey().observe(.childAdded, with: {
snapshot in
let snapshotValue = snapshot.value as? NSDictionary
let title = snapshotValue?["title"] as? String
let message = snapshotValue?["message"] as? String
self.posts.insert(PostStruct(title: title ?? "", message: message ?? ""), at: 0)
self.tableView.reloadData()
})
post()
}
func post(){
let title = "Title"
let message = "Message"
let post : [String : AnyObject] = ["title" : title as AnyObject, "message" : message as AnyObject]
let databaseRef = Database.database().reference()
databaseRef.child("Posts").childByAutoId().setValue(post)
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return posts.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
let label1 = cell.viewWithTag(1)as! UILabel
label1.text=posts[indexPath.row].title
let label2 = cell.viewWithTag(2)as! UILabel // Error code: thread 1 exc_bad_instruction (code=exc_i386_invop subcode=0x0)
label2.text=posts[indexPath.row].message
return cell
}
}
答案 0 :(得分:0)
线程1 exc_bad_instruction(code = exc_i386_invop subcode = 0x0)错误意味着应用程序已经确定元素应该存在,因此当它没有
时会崩溃在您的情况下,可能有两个原因导致这种情况发生:
崩溃的原因应该是其中之一。
答案 1 :(得分:0)
该行:
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
表示您正在返回UITableViewCell。基本的默认样式没有2个标签。因此,要么更改dequeReusableCell以返回自定义单元格:
if let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as? MyCustomCellView {
//MyCustomCellView would be your UITableViewCell implementation
let label1 = cell.viewWithTag(1)as! UILabel
label1.text=posts[indexPath.row].title
let label2 = cell.viewWithTag(2)as! UILabel
label2.text=posts[indexPath.row].message
}
或将单元格样式更改为副标题(这样您可能会获得第二个标签)