Aliou Aliou - 5 months ago 38
Swift Question

UITableViewController with custom data source not showing cells

I currently have a UITableViewController that sets up a custom data source in its init function:

class BookmarkTableViewController: UITableViewController {
var date: Date

// MARK: - Init
init(date: Date, fetchAtLoad: Bool) {
self.date = date
super.init(style: .plain)
self.tableView.dataSource = BookmarkDataSource(date: date)
self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
}

// ...
}


The custom data source is as follows:

class BookmarkDataSource: NSObject {
let date: Date

init(date: Date) {
self.date = date
super.init()
}
}

// MARK: - UITableViewDataSource
extension BookmarkDataSource: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 3
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell()
cell.textLabel?.text = "Test content"

return cell
}
}


However when I run on the simulator or on a device nothing shows up in the table view. Does anyone know what I'm missing?

Note: I'm using Xcode 8.0 Beta and Swift 3.

Answer

You need to store a strong reference to your BookmarkDataSource object. The dataSource of tableView becomes nil with the code you posted.

class BookmarkTableViewController: UITableViewController {
    var date: Date
    var dataSource:BookmarkDataSource

    // MARK: - Init
    init(date: Date, fetchAtLoad: Bool) {
        self.date = date
        super.init(style: .plain)
        dataSource = BookmarkDataSource(date: date)
        self.tableView.dataSource = dataSource
        self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
    }

    // ...
}