2017-06-20 55 views
0

我试图从AppDelegate注入一个对象到UIViewController中,但我不确定我是否正确地做到了这一点。请有人建议。当我在标有'THE ERROR OCCURS HERE'的代码行开始我的应用程序时,出现错误。从AppDelegate注入对象到UIViewController

enter image description here

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) 
+0

它看起来像你还没有初始化'itemstore'对象 –

+0

它似乎你没有将'testController'设置为'rootViewController'。 – ovo

回答

1

您实例化AppDelegate视图控制器,但该系统将创建视图控制器类的其他实例,因此显示不具有itemstore的类的一个实例财产初始化。 您必须使itemstore变为一个类型变量而不是实例变量,或者如果您只需要此功能用于您的根视图控制器,则必须实例化您的根视图控制器实例的itemstore变量,您知道这个变量是使用的变量由您的导航控制器。

+0

所以你的意思是我应该在我的TestTableViewController中实例化一个ItemStore实例? – tim

+0

不可以。如果您在AppDelegate中获取实例化一个'ItemStore'实例所需的数据,则需要将该对象传递给导航控制器视图层次结构中的'TestTableViewController'。为了达到这个目的,你必须在我的答案中提出两种方法中的一种。 –