我试图在UITabBarController内部的UITableView中显示一些(现在硬编码)数据,但是我在填充行时遇到了困难。
这是我的数据对象的代码(Reservation.swift)
import UIKit
class Reservation: NSObject {
var tailNumber: String
var aircraftType: String
var arrivalTime: String
var eta: String
init(tailNumber: String, aircraftType: String, arrivalTime: String, eta: String) {
self.tailNumber = tailNumber
self.aircraftType = aircraftType
self.arrivalTime = arrivalTime
self.eta = eta
super.init()
}
}
以下是我的预订商店(ReservationStore.swift)的代码
import UIKit
class ReservationStore {
// Store all our schedules
var allReservations = [Reservation]()
func createReservation() -> Reservation {
let newReservation = Reservation(tailNumber: "N53440", aircraftType: "C172S", arrivalTime: "07-06-2016 07:00am", eta: "1:58")
allReservations.append(newReservation)
return newReservation
}
init() {
createReservation()
}
}
这是我的UITableView视图控制器(ScheduleViewController.swift)
import UIKit
class ScheduleViewController: UITableViewController {
var reservationStore: ReservationStore!
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return reservationStore.allReservations.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("UITableViewCell", forIndexPath: indexPath)
let item = reservationStore.allReservations[indexPath.row]
cell.textLabel?.text = item.tailNumber
return cell
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
let reservationStore = ReservationStore()
let tabController = segue.destinationViewController as! UITabBarController
let reservationController = tabController.viewControllers![1] as! ScheduleViewController
reservationController.reservationStore = reservationStore
}
}
我收到致命错误:在返回reservationStore.allReservations.count时解包可选值时意外发现nil
我相信,当用户在视图加载之前单击日程表的UITabController项时,会调用prepareForSegue。这应该触发我的ReservationStore中的init()并在数组中创建一个元素,但我不相信这种情况正在发生,因为它在数组计算时是否为零?
也许这个创作应该在prepareForSegue中?一段时间以来一直在搞乱这个问题,不知道接下来要去哪里,有人能指出我正确的方向吗?
答案 0 :(得分:1)
prepareForSegue()
。当 视图控制器准备转换为新视图控制器时,会调用它。没有任何内容分配给您的ScheduleViewController
reservationStore
属性,因此它是nil
,因此崩溃。
如果您要做的只是将ReservationStore
的实例分配给该属性,则可以在定义属性时将其设置为默认值:
class ScheduleViewController: UITableViewController {
var reservationStore = ReservationStore()
// …
}