没有调用TableView的cellForRowAtIndexPath?

问题描述:

我想在Swift中构建一个简单的TableView,但不是遵守我的ViewController中的数据源协议,而是想创建一个新的类作为DataSource。不幸的是,通过这种方法,我无法在我的ViewController中加载任何内容。没有调用TableView的cellForRowAtIndexPath?

这是我的ViewController类:

class SaladViewController: UIViewController { 

    @IBOutlet weak var saladTable: UITableView! 

    override func viewDidLoad() { 
     super.viewDidLoad() 

     // Do any additional setup after loading the view. 

     let tableData = LunchTableData() 
     self.saladTable.dataSource = tableData 
    } 

    override func didReceiveMemoryWarning() { 
     super.didReceiveMemoryWarning() 
     // Dispose of any resources that can be recreated. 
    } 
} 

这是我的DataSource类:

class LunchTableData: NSObject, UITableViewDataSource { 

    var things = ["One", "Two", "Three"] 

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 
     return things.count 
    } 

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 
     let cell = tableView.dequeueReusableCellWithIdentifier("cell") 

     let itemText = cell!.viewWithTag(100) as! UILabel 
     itemText.text = things[indexPath.row] 

     return cell! 
    } 
} 

RowAtIndexPath获取调用很好,所以我只是不知道为什么的cellForRowAtIndexPath不是永远被称为。我设置了一个断点,它从来没有打过它。

谢谢你的帮助!

我觉得tableData在viewDidLoad()完成后被销毁。

因此,在@IBOutlet弱变色表的下方移动以下行:UITableView!线。

let tableData = LunchTableData() 

希望这有助于你

所以完整的代码

class SaladViewController: UIViewController { 

    @IBOutlet weak var saladTable: UITableView! 

    let tableData = LunchTableData() 

    override func viewDidLoad() { 
     super.viewDidLoad() 

     // Do any additional setup after loading the view. 

     self.saladTable.dataSource = tableData 
    } 

    override func didReceiveMemoryWarning() { 
     super.didReceiveMemoryWarning() 
     // Dispose of any resources that can be recreated. 
    } 
} 
+2

这是需要做什么。表格数据被声明为局部变量,这意味着当它的作用域结束时它会被销毁,在你的情况下,当'viewDidLoad()'完成时。 – NRitH

+2

是的,数据源属性是'weak'。 – rmaddy

+0

就是这样!谢谢!忘记变量范围......此外,Swift中“弱”与“强”意味着什么? – CPL