xcode 如何以编程方式设置 UITableView 的数据源?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25075646/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 05:18:55  来源:igfitidea点击:

How can I programmatically set dataSource of UITableView?

iosxcodeuitableviewswift

提问by sina

I am having a strange problem. I am trying to assign a dataSource to a table programatically.

我有一个奇怪的问题。我正在尝试以编程方式将数据源分配给表。

I have created a UITableViewand an IBOutlet for it in my ViewController using the Interface Builder. I have created a class that implements UITableViewDataSource. I set the dataSourceof 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.

UITableView使用 Interface Builder 在我的 ViewController 中为它创建了一个和一个 IBOutlet。我创建了一个实现UITableViewDataSource. 我将dataSource表的 设置为数据源的一个实例。一切都编译并运行良好,直到在运行时执行设置 dataSource 的行。

The error is Thread 1: EXC_BAD_ACCESS (code=EXC_i386_GPFLT)and the class AppDelegatedefinition line is highlighted.

错误是Thread 1: EXC_BAD_ACCESS (code=EXC_i386_GPFLT)并且class AppDelegate定义行突出显示。

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.

任何想法为什么我会收到此运行时错误?我在 Swift 中使用 XCode 6 beta 4。

回答by RaffAl

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 dsis deallocated as soon as viewDidLoadreturns. You have to keep a reference to your data source.

您的应用程序中断,因为它在返回后ds立即被释放viewDidLoad。您必须保留对数据源的引用。