2016-02-13 36 views
0

我有兩個類:如何創造一個UITableView的類的實例在迅速

//This is my custom class, where I would like to get access to 'MyTableView' class 

import UIKit 

class TestClass: NSObject { 

    //Instance variable 'myTableView' 
    var myTableView: MyTableView! 

    override init() { 
     super.init() 

     //Creat an instance! 
     myTableView = MyTableView() 
    } 

    func ReloadTableView() { 

     //Reload the current TableView 
     myTableView.MyTableView.reloadData() 
    } 
    //My functions... 
} 

//This is 'MyTableView' class which is connected to a TableViewController in storyboard. When I open the corresponding TableView in my App, the viewDidLoad function is called. 
import UIKit 
class MyTableView: UITableViewController { 

    @IBOutlet var MyTableView: UITableView! 

    override func viewDidLoad() { 
     super.viewDidLoad() 
    } 

    override func didReceiveMemoryWarning() { 
     super.didReceiveMemoryWarning() 
    } 

//Functions to creat the current TableView with it's information... 
} 

我的問題:

爲什麼我不能從'TestClass'訪問'MyTableView'類?我總是得到例外:

unexpectedly found nil while unwrapping an Optional value

有沒有可能獲得有關活動視圖的信息? 謝謝!

回答

2
  1. 你不應該使用變量名與大寫字母開始,如:

    @IBOutlet VAR MyTableView:UITableView的!

這是不好的做法,並可能導致混亂的代碼

  • 你的MyTableView類的實例是簡單地調用它的默認構造函數,在這個案例不會在該類中實例化MyTableView屬性。你必須從情節串連圖板用這樣的實例是:

    self.storyboard.instantiateViewControllerWithIdentifier("MyTableViewIdentifier") 
    
  • +1

    要在此補充,在'類MyTableView'應該被重新命名爲'爲清楚起見類MyTableViewController'。 – xoudini

    +0

    好的,這似乎是一個好方法:)但我不明白如何實施您的解決方案。當我試圖在我的TestClass中實現你的代碼時,它會說:「類型TestClass的值沒有成員'storyboard'」所以我將你的代碼改成了self。 myTableView.storyboard.instantiateViewControllerWithIdentifier(「MyTableViewIdentifier」)'...現在我得到同樣的錯誤:意外地發現無,而... – Passe

    +0

    'storyboard'是視圖控制器上的屬性。如果您沒有以前從故事板加載的視圖控制器的實際實例,則可以使用'UIStoryboard(名稱:「MyStoryboard」,捆綁包:NSBundle.mainBundle())實例化故事板。 –