如何以编程方式设置UITableView的dataSource? [英] How can I programmatically set dataSource of UITableView?
问题描述
我遇到了一个奇怪的问题。我正在尝试以编程方式将dataSource分配给表。
I am having a strange problem. I am trying to assign a dataSource to a table programatically.
我已经为它创建了一个 UITableView
和一个IBOutlet在我的ViewController中使用Interface Builder。我创建了一个实现 UITableViewDataSource
的类。我将我的表的 dataSource
设置为dataSource的一个实例。 Everything编译并运行正常,直到设置dataSource的行在运行时执行。
I have created a UITableView
and an IBOutlet for it in my ViewController using the Interface Builder. I have created a class that implements UITableViewDataSource
. I set the dataSource
of my table to be an instance of the dataSource. Everything compiles and runs fine, until the line that sets the dataSource is executed in runtime.
错误是线程1:EXC_BAD_ACCESS(代码= EXC_i386_GPFLT )
并突出显示类AppDelegate
定义行。
The error is Thread 1: EXC_BAD_ACCESS (code=EXC_i386_GPFLT)
and the class AppDelegate
definition line is highlighted.
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
}
}
我收到此运行时错误的任何想法?我正在使用XCode 6 beta 4和Swift。
Any ideas why I am getting this runtime error? I am using XCode 6 beta 4 with Swift.
推荐答案
将您的代码更改为:
class ViewController: UIViewController
{
@IBOutlet weak var table: UITableView!
var dataSource: MyData?
override func viewDidLoad()
{
super.viewDidLoad()
dataSource = MyData()
table.dataSource = dataSource!
}
}
你的应用程序因为而中断只要
。您必须保留对数据源的引用。 viewDidLoad
返回,就会释放ds
Your app breaks because the ds
is deallocated as soon as viewDidLoad
returns. You have to keep a reference to your data source.
这篇关于如何以编程方式设置UITableView的dataSource?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!