斯威夫特:无法将我的价值投入标签(可选问题)

时间:2018-12-05 09:18:55

标签: ios swift

我从Firebase获得了我的价值,但是Swift不想将其放在标签中。

  

线程1:致命错误:在展开可选值时意外发现nil

总而言之,我的数据库如下所示: Firebase database

我已经创建了一个标准模型,称为ServiceModel:

import Foundation

class ServiceModel {

    var name: String?
    var category: String?
    var pricing: String?

    init(name: String?, category: String?, pricing: String?){
        self.name = name
        self.category = category
        self.pricing = pricing
    }
}

我想将此值显示到TableView中,所以我创建了一个这样的自定义单元格(也非常标准):

import UIKit

class SubscriptionTableViewCell: UITableViewCell {

    @IBOutlet weak var imageService: UIImageView!
    @IBOutlet weak var labelName: UILabel!
    @IBOutlet weak var labelCategory: UILabel!
    @IBOutlet weak var labelPricing: UILabel!

    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }

}

现在,这是我视图的控制器:

import UIKit
import FirebaseDatabase

class SecondViewController: UIViewController,UITableViewDelegate, UITableViewDataSource {

    var refServices:DatabaseReference!

    @IBOutlet weak var ListSub: UITableView!

    var serviceList = [ServiceModel]()

    var databaseHandle:DatabaseHandle?

    public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        return serviceList.count
    }

    public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

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

        let service: ServiceModel

        service = serviceList[indexPath.row]

        //cell.imageService.image = UIImage(named: service.name! + ".png")
        cell.labelName?.text = service.name //ERROR HERE
        cell.labelCategory?.text = service.category
        cell.labelPricing?.text = service.pricing

        return cell
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        ListSub.delegate = self
        ListSub.dataSource = self

        refServices = Database.database().reference().child("Categories");

        refServices.observe(DataEventType.value, with: { (snapshot) in

            if snapshot.childrenCount > 0 {

                self.serviceList.removeAll()

                for services in snapshot.children.allObjects as! [DataSnapshot] {
                    let serviceObject = services.value as? [String: AnyObject]
                    let serviceName  = serviceObject?["Name"]
                    let serviceCategory  = serviceObject?["Category"]
                    let servicePricing = serviceObject?["Pricing"]
                    let service = ServiceModel(name: serviceName as! String?, category: serviceCategory as! String?, pricing: servicePricing as! String?)

                    self.serviceList.append(service)
                }

                self.ListSub.reloadData()
            }
        })
    }

启动此视图时,出现前面提到的错误。 调试时,我发现在service.name,service.category和service.pricing中有正确的值

似乎我没有正确处理可选值,但看不到有什么问题。

感谢您的帮助。

4 个答案:

答案 0 :(得分:0)

如果调试此功能,您会从服务中看到什么

public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

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

    let service: ServiceModel

    //Put a breakpoint here
    service = serviceList[indexPath.row]
    //Put a breakpoint here

    //cell.imageService.image = UIImage(named: service.name! + ".png")
    cell.labelName?.text = service.name
    cell.labelCategory?.text = service.category
    cell.labelPricing?.text = service.pricing

    return cell
}

答案 1 :(得分:0)

在可选展开时可能会崩溃的行是此行

    refServices = Database.database().reference().child("Categories");
    refServices.observe(DataEventType.value, with: { (snapshot) in

尝试设置断点,并检查refServices是否正确初始化,或者不使用!将ti设为可选参数

希望获得帮助

Ps。请从您的Swift代码中删除;:P

答案 2 :(得分:0)

使用此代码:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(withIdentifier: "SubCell", for: indexPath) as! SubscriptionTableViewCell
    let service = serviceList[indexPath.row]

    // If you sure that you have to display all the info use this code
    if let name = service.name, let category = service.category, let price = service.pricing {
        cell.labelName.text = name
        // set other data also here....
    }


    // If you know any value may be empty or not exists then use this code.
    if let name = service.name {
        cell.labelName.text = name
    }

    if let category = service.category {
        cell.labelCategory.text = service
    }

    if let pricing = service.pricing {
        cell.labelPricing.text = pricing
    }
    return cell
}

答案 3 :(得分:0)

您是否在tableView中注册了自定义UITableViewCell?将此行放入您的ViewController的init()函数中:

ListSub.register(SubscriptionTableViewCell.classForCoder(), forCellReuseIdentifier: "SubCell")