I am having a strange problem. I am trying to assign a dataSource to a table programatically.
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.
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
}
}
Any ideas why I am getting this runtime error? I am using XCode 6 beta 4 with Swift.
dataSourcedelegate is usually aweakproperty, and you are not keeping yourdsalive with a strong pointer outside of the scope, so that will be released immediately when the–viewDidLoad()runs out of its own scope... that may cause your problem here.table.dataSourceby reference, not by value? If it was set by value would the code have worked?