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.
Change your code to:
class ViewController: UIViewController
{
@IBOutlet weak var table: UITableView!
var dataSource: MyData?
override func viewDidLoad()
{
super.viewDidLoad()
dataSource = MyData()
table.dataSource = dataSource!
}
}
Your app breaks because the ds is deallocated as soon as viewDidLoad returns. You have to keep a reference to your data source.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With