How can I programmatically set dataSource of UITableView?

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.

  • SWRevealViewController FrontViewController not loading, stuck as Black, other views fine
  • Swift: Custom camera save modified metadata with image
  • AlamoFire asynchronous completionHandler for JSON request
  • iOS5 NSURLConnection methods deprecated
  • iOS version of Fragments
  • Swift PDF create Rectangle?
  • 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.

    Solutions Collect From Internet About “How can I programmatically set dataSource of UITableView?”

    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.