我试图从AppDelegate注入一个对象到UIViewController中,但我不确定我是否正确地做到了这一点。请有人建议。当我在标有'THE ERROR OCCURS HERE'的代码行开始我的应用程序时,出现错误。从AppDelegate注入对象到UIViewController
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Create ItemStore instance
let itemStoreObject = ItemStore()
let storyBoard: UIStoryboard = UIStoryboard.init(name: "Main", bundle: nil)
let testController = storyBoard.instantiateViewController(withIdentifier: "testTableController") as! TestTableViewController
testController.itemstore = itemStoreObject
return true
}
ItemStore:
import UIKit
class ItemStore {
var allItems = ["Thanh", "David", "Tommy", "Maria"]
}
TestTableViewController:
class TestTableViewController: UIViewController, UITableViewDelegate, UISearchBarDelegate, UITableViewDataSource{
@IBOutlet var myTableView: UITableView!
var itemstore: ItemStore!
override func viewDidLoad() {
super.viewDidLoad()
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
print("numberOfRowsSection ...")
return itemstore.allItems.count // THE ERROR OCCURS HERE.
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
print("cellForRow ...")
// Get a new or recycled cell
let cell = UITableViewCell(style: .value1, reuseIdentifier: "UITableViewCell")
let name = itemstore.allItems[indexPath.row]
cell.textLabel?.text = name
return cell
}
}
我收到以下错误信息(标在“线错误发生时该处”):
fatal error: unexpectedly found nil while unwrapping an Optional value
(lldb)
它看起来像你还没有初始化'itemstore'对象 –
它似乎你没有将'testController'设置为'rootViewController'。 – ovo