Swift Subclassing UITableViewDataSource EXC_BAD_ACCESS

假如想象 提交于 2019-12-08 04:29:51

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!