How to set the datasource of a UITableView in code

ios, objective-c, uitableview

Solution

'UITableView dataSource must return a cell from tableView:cellForRowAtIndexPath:'

This is what is causing your app to crash. Something in the logic of your `tableView:cellForRowAtIndexPath` method is keeping a `UITableViewCell` from being returned. That log message says it all -- A `UITableViewCell` must be returned from `tableView:cellForRowAtIndexPath:`.

Problem

I know this question is other places on stackoverflow, but none of those solutions have worked for me. I have two tabs with table views that I want using the same datasource. The first tab's view controller is a subclass of `UITableViewController`. The second one is a simple `UIViewController` with its tableView set up in IB. I initially set up the view controller initializer to take the data source as an argument, but since that was crashing so much, I tried to simplify things by simply allocating it in my view controller. I have the Table View and datasource set up as follows: ``` @property (weak, nonatomic) IBOutlet UITableView *tableView; //Connected in IB @property (strong, nonatomic) TableViewDataSource *data; ``` My program always crashes whenever I: `[self.tableView setDataSource: data];` I tried putting that line in the `viewDidLoad` method, but my program still crashes. Here is my `viewDidLoad` method: ``` - (void)viewDidLoad { [super viewDidLoad]; data = [TableViewDataSource new]; //My data source object NSLog(@"%@", data); //This isn't null, it says TableViewDataSource and then some address [self.tableView setDataSource:data]; } ``` My first view controller works fine. It loads the data fine as well, so I don't believe I made any mistake in my datasource object. But every time I click on the second tab, the program crashes immediately. It doesn't crash if I leave out the data source assignment statement however. Here is the crash: ``` 2013-08-14 12:56:57.313 iPlanner[961:c07] *** Assertion failure in -[UITableView _configureCellForDisplay:forIndexPath:], /SourceCache/UIKit_Sim/UIKit-2380.17/UITableView.m:5471 2013-08-14 12:56:57.314 iPlanner[961:c07] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'UITableView dataSource must return a cell from tableView:cellForRowAtIndexPath:' *** First throw call stack: (0x1ca2012 0x10dfe7e 0x1ca1e78 0xb75665 0xd9c1b 0x6e40c 0xd9a7b 0xde919 0xde9cf 0xc71bb 0xd7b4b 0x742dd 0x10f36b0 0x229efc0 0x229333c 0x2293150 0x22110bc 0x2212227 0x22b4b50 0x39edf 0x1c6aafe 0x1c6aa3d 0x1c487c2 0x1c47f44 0x1c47e1b 0x1bfc7e3 0x1bfc668 0x23ffc 0x298d 0x28b5) libc++abi.dylib: terminate called throwing an exception (lldb) ```

Original source