Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
339 views
in Technique[技术] by (71.8m points)

ios - 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.

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...