如何用我在ViewDidLoad上接收的数据填充UITableView?



我正在尝试使用Alamofire获取一些数据,并尝试将其中一些数据放入数组

class BaseFormViewController : UIViewController, UITableViewDelegate, UITableViewDataSource {
let colorPalette = VOCColorPaletteManager()
let form = GetEmployeeCompositionApp()
let baseUrl = url
let parameters = parameters
var jsonData : EmployeeCompositionApp?
var separators : [Separator]?
// ------ IBOutlets ------
@IBOutlet weak var formTableView: UITableView!
/***   TableView   ***/
var xibCell = "BaseFormCell"
var reuseIdentifier = "BaseFormCell"

override func viewDidLoad() {
    super.viewDidLoad()
    self.view.backgroundColor = colorPalette.clearGrayColorObject()
    self.formTableView.delegate = self
    self.formTableView.dataSource = self
    self.formTableView.register(UINib(nibName: xibCell, bundle: nil), forCellReuseIdentifier: reuseIdentifier)
    requestAllForms()
}

viewdidload中的 requestAllForms()是我用来获取这些数据的方法

 func requestAllForms() {
        /*****    Petición a API    *****/
    Alamofire.request(baseUrl,
                      method: .post,
                      parameters: parameters)
        .responseJSON { response in
            guard response.result.error == nil else {
                print("Error en petición a Alamofire:n (String(describing: response.result.error))")
                return
            }
            guard let json = response.result.value as? [String : Any] else {
                print("No se ha podido extraer un archivo JSON")
                if let error = response.result.error {
                    print("Error : (error.localizedDescription)")
                }
                return
            }
            /******    Parseado de JSON    *****/
            do {
                let decoder = JSONDecoder()
                let rawData = try JSONSerialization.data(withJSONObject: json, options: [])
                let objectData = try decoder.decode(EmployeeCompositionApp.self, from: rawData)
                self.jsonData = objectData
            /*****    Metiendo datos en los arrays correspondientes    *****/
                for item in objectData.data.elements.separators {
                    self.separators?.append(item)
                }
                self.formTableView.reloadData()

            } catch let error {
                print("Error: n", error)
            }
    }
}

但是,当我尝试访问viewController崩溃时,我认为这是因为数组中没有任何东西

func numberOfSections(in tableView: UITableView) -> Int {
    return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return (separators?.count)!
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: reuseIdentifier, for: indexPath) as! BaseFormCell
    for item in (jsonData?.data.elements.separators)! {

        separators.append(item)
        cell.idLabel.text = item.separatorId
        cell.nameLabel.text = item.name
        cell.typeLabel.text = item.separatorType
        let separatorsID = item.separatorId
        cell.idLabel.text = separatorsID
        print("separators id: (separatorsID)")
        let separatorsName = item.name
        cell.idLabel.text = separatorsName
        let separatorType = item.separatorType
        cell.idLabel.text = separatorType
    }

    return cell
}

当它在控制台上崩溃时,只有(lldb)

和Xcode给出了错误

Thread 1: EXC_BREAKPOINT (code=1, subcode=0x103216bdc)

我在做什么错?有没有更好的方法来使用我从JSON获得的对象,而不是将它们放入闭合内的数组中?

谢谢

当调用NumberOfrowsInsection时,您的分离器永远不会初始化。

您的分离器属性实际上永远不会在您的代码中初始化。分离器将附加在您的Alamofire闭合中,即异步。但是,您的分离器尚未初始化,因此无能为力。

var separators : [Separator]? 
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return (separators?.count)! // Force unwrapping nil will cause crash
    return separators?.count ?? 0 // Safely unwrap like so.. Default 0 if separators is nil
}
// Alamofire closure
for item in objectData.data.elements.separators {
  self.separators?.append(item) // Appending to uninitialized array
}

更好的是,没有分离器作为可选的。您可能必须解决可选的链式错误。

var separators = [Separator]()
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return separators.count
}

您应该在以下数字中放入数字: -

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    if separators != nil{
    return (separators?.count)!
   }
return 0
}

您的应用程序崩溃了,因为可能有一些场景,海港数组没有值,而您正在尝试使用nil Array填充它。

最新更新