2016-02-13 45 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())实例化故事板。 –