与nIl打交道?在UITableViewCell

时间:2018-12-06 11:17:17

标签: ios swift null

好吧,在解决了“自我”问题之后,我现在正在努力理解为什么我不能从MysqlDB中解开结果。该应用会连接,检索数据,然后可能会显示它们。问题在于它无法解包。这里的代码

ViewController.swift

import UIKit
 class ViewController: UIViewController, UITableViewDataSource,     UITableViewDelegate, HomeModelProtocol {

//downloadItems
func itemsDownloaded(items: NSArray) {
    feedItems = items
    self.listTable.reloadData()
}

//link tV
@IBOutlet weak var listTable: UITableView!
//Proprietà
var feedItems: NSArray = NSArray()
var selectList : ListModel = ListModel()



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

//viewDidLoad
override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    //set delegates and initialize a homeModel
    self.listTable.delegate = self
    self.listTable.dataSource = self

    let homeModel = HomeModel ()
    homeModel.delegate = self
    homeModel.downloadItems()
}


func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) ->UITableViewCell {
    let cellIdentifier : String = "BasicCell"
    let myCell: UITableViewCell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier)!

    //recupero food
    let item : ListModel = feedItems[indexPath.row] as! ListModel

    //reference alla label
    myCell.textLabel!.text = item.description

    return myCell
}}

ListModel.swift

import Foundation
class ListModel : NSObject {

//proprietà
var name: String?
var percentage: Int?
var other: String?
var id: Int?


override init(){
}

init(name: String, percentage: Int, other: String, id: Int){
    self.name = name
    self.percentage = percentage
    self.other = other
    self.id = id
}

//stampa oggetti
override var description: String{
    return "Name: \(name), Percentuale: \(String(describing: percentage)), Altro: \(other)"
}}

HomeModel.swift

import Foundation

protocol HomeModelProtocol: class {
    func itemsDownloaded(items: NSArray)
} 

class HomeModel: NSObject, URLSessionDataDelegate{
//proprietà
weak var delegate: HomeModelProtocol!
var data = Data()
let urlPath: String = "http://www.sake-house.net/webServices.php"

func downloadItems(){
    let url : URL = URL(string: urlPath)!
    let defaultSession = Foundation.URLSession(configuration: URLSessionConfiguration.default)
    let task = defaultSession.dataTask(with: url) {(data, response, error) in
        if error != nil{
            print("downloasd fallito")
        }else{
            print("Dati scaricati")
            parseJSON(data!)
        }
    }
    task.resume()
}} 
func parseJSON(_ data:Data){
var jsonResult = NSArray()

do{
    jsonResult = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.allowFragments) as! NSArray
} catch let error as NSError{
    print (error)
}

var jsonElement = NSDictionary()
let listFoods = NSMutableArray()

for i in 0..<jsonResult.count {
    jsonElement = jsonResult[i] as! NSDictionary

    let listF = ListModel()

    if let name = jsonElement["Name"] as? String, let percentage = jsonElement["Percentage"] as? Int, let other = jsonElement["other"] as? String, let id = jsonElement["id"] as? Int{
        listF.name = name
        listF.percentage = percentage
        listF.other = other
        listF.id = id
    }
    listFoods.add(listF)

    //check listFoods
    DispatchQueue.main.async(execute: { () -> Void in self.delegate.itemsDownload(items: listFoods)}) <--------HERE

}}//fine func parseJSON

问题在这一行

let myCell: UITableViewCell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier)!
  

“线程1:致命错误:展开一个可选值时意外发现nil”

ViewController.swift中。如果我删除此行,则可以正常显示名称:无

2 个答案:

答案 0 :(得分:1)

此行崩溃

 let myCell: UITableViewCell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier)!

由于您需要为该tableView注册单元格,因此需要创建一个自定义单元格,然后使用

let myCell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier) as! CellName

注册

tableView.register(CellName.self, forCellReuseIdentifier:cellIdentifier)

//或xib

tableView.register(UINib(nibName: "xibname", bundle: nil), forCellReuseIdentifier: cellIdentifier)

class CellName:UITableViewCell {

   // outlets here 

}

答案 1 :(得分:0)

所以,我按照Sh_Khan所说的尝试过。我想我遗漏了一些东西,或者根本做错了。内部Viecontroller.swift

class CellName:UITableViewCell {

}
@IBOutlet weak var listTable: UITableView!

然后

tableView.register(CellName.self, forCellReuseIdentifier:cellIdentifier)
let myCell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier) as! CellName

现在我可以看到一些东西,但结果却看到“无”