我怎样才能以编程方式设置UITableView的dataSource?
我有一个奇怪的问题。 我正试图分配一个数据源以编程方式表。
我已经使用Interface Builder在ViewController中创build了一个UITableView
和一个IBOutlet。 我创build了一个实现UITableViewDataSource
的类。 我将我的表的dataSource
设置为dataSource
的一个实例。 一切编译并运行正常,直到设置dataSource的行在运行时执行。
错误是Thread 1: EXC_BAD_ACCESS (code=EXC_i386_GPFLT)
,并且class AppDelegate
定义线被突出显示。
class ViewController: UIViewController { @IBOutlet weak var table: UITableView! override func viewDidLoad() { let ds = MyData() table.dataSource = ds // <---- Runtime error table.reloadData() super.viewDidLoad() } // ... other methods } class MyData: NSObject, UITableViewDataSource { func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int { return 5 } func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! { let cell = UITableViewCell() cell.textLabel.text = "a row" return cell } }
任何想法,为什么我得到这个运行时错误? 我正在用Swift使用XCode 6 beta 4。
将您的代码更改为:
class ViewController: UIViewController { @IBOutlet weak var table: UITableView! var dataSource: MyData? override func viewDidLoad() { super.viewDidLoad() dataSource = MyData() table.dataSource = dataSource! } }
你的应用程序中断,因为只要viewDidLoad
返回ds
被释放。 你必须保留对你的数据源的引用。