2017-06-20 42 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'。爲了達到這個目的,你必須在我的答案中提出兩種方法中的一種。 –

相關問題