问题
I am trying To subclass My UITableViewDatasource, However My App Crashes with EXC_BAD_ACCESS. No explanations no error messages just crashes. A Sort Version of my DataSource Looks Like This.
import UIKit
class DataSource :NSObject, UITableViewDataSource{
var tableView:UITableView
let CellIdentifier = "Cell"
init(tableView : UITableView) {
println("Data Source")
self.tableView = tableView
super.init()
self.tableView.dataSource = self
}
//:MARK UITableViewDataSource
//-----------------------------------------------------------------------------------------//
// Number Of Rows In Tableview
//-----------------------------------------------------------------------------------------//
func tableView(tableView: UITableView?, numberOfRowsInSection section: Int) -> Int
{
return 10
}
//-----------------------------------------------------------------------------------------//
// Cell For Row At Index Path
//-----------------------------------------------------------------------------------------//
func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! {
let cell = self.tableView.dequeueReusableCellWithIdentifier(CellIdentifier, forIndexPath: indexPath) as UITableViewCell
cell.textLabel.text = "Title of Row: #\(indexPath.row)"
return cell
}
}
As You can see There is nothing special, this code works fine in Playground
Below is my call to DataSource
import UIKit
class ListEntriesViewController :UITableViewController{
override func viewDidLoad() {
println("View Did Load")
var data = DataSource(tableView: self.tableView)
self.tableView.dataSource = data
}
}
What Am I missing, Why this code works works in Playground but not in my App.
Thank You
回答1:
The datasource is not retained by the table view. The object is destroyed immediately after viewDidLoad. You need to store it in a property.
Also note that UITableViewDataSource is a protocol, not a class. Hence it can't be subclassed.
来源:https://stackoverflow.com/questions/24887727/swift-subclassing-uitableviewdatasource-exc-bad-access