2017-06-20 4 views
0

私はAppDelegateからUIViewControllerにオブジェクトを注入しようとしていますが、正しく行っているかどうかはわかりません。誰か助言してください。 「エラーが発生しました」という行のコード行でアプリケーションを起動すると、エラーが発生します。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 
} 

} 

私は、次のエラーメッセージ(マークを取得ライン「ERRORがHERE OCCURS」)で:

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'に渡す必要があります。これを達成するには、私が私の答えで提案した2つの方法のうちの1つを行う必要があります。 –

関連する問題