繁体   English   中英

无法从父级ViewController在UITableViewCell中设置变量

[英]Unable to set a variable in UITableViewCell from parent ViewController

我有一个UITableView和一个自定义TableViewCell类,我在viewDidLoad方法中设置了非null值,但是在cellForRow方法中将值设置为UITableViewCell时,该值神奇地变成了nil。 我无法从我的自定义UITableViewCell访问set变量。这是代码段。 ViewDidLoad中的Print语句将打印该值,而cellForRowAtIndexPath中的一个则返回nil

override func viewDidLoad() {
    super.viewDidLoad()
    Docco360Util.shared().getDoctorsWithResultBlock { (doctorObjects, error) in
        if let err = error{
            print(err)
        }else{
            self.doctors=doctorObjects
            print(doctorObjects![1].professionalHeader)//output is printed here
            self.doctorTableView.reloadData()
        }
    }

    // Do any additional setup after loading the view.
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let identifierForUsers = "DoctorTableViewCell"
    var cell = tableView.dequeueReusableCell(withIdentifier: identifierForUsers, for: indexPath) as! DoctorTableViewCell
    if cell == nil{
        cell=DoctorTableViewCell(style: .default, reuseIdentifier: identifierForUsers)
    }
    print(self.doctors[indexPath.row].professionalHeader)//output in nil here
    cell.doctor=self.doctors[indexPath.row]
    return cell
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(withIdentifier: "DoctorTableViewCell", for: indexPath) as! DoctorTableViewCell

    print(self.doctors[indexPath.row].professionalHeader)
    cell.doctor = self.doctors[indexPath.row]
    return cell
}

首先,您应确保在主(UI)线程中执行Docco360Util.shared().getDoctorsWithResultBlock的关闭。 如果不是,则应将其放入DispatchQueue.main.async块中。

然后,您应该验证结果块是否已执行(例如,print语句打印出一些内容)。 顺便说一句,为什么您用索引1而不是0调用print(doctorObjects![1].professionalHeader) tableView(tableView:cellForRowAt:)您的元素索引为0也许这位doctor nil

您可以从为属性声明,观察点设置断点开始,或者实现一个属性观察器( willSet )并willSet添加断点,以检查是否有人弄乱了您的变量。

如果所有这些都无济于事,则您可能想发布更多代码,尤其是编写self.doctors数组的所有代码行。

我终于可以解决它。 问题出在变量的声明中。 我正在使用Objective-C头文件进行声明。 在声明我将它们声明为“弱”而不是“保留”时,这就是造成问题的原因。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM