【问题标题】:How to solve this error in Swift?如何在 Swift 中解决这个错误?
【发布时间】:2017-07-29 06:28:11
【问题描述】:

我在控制台中收到以下错误:

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

并在 Xcode 编辑器中显示如下错误:

线程 1 EXC_BAD_INSTRUCTION(code=EXC_I386_INVOP,subcode=0*0)

我在 Swift 3 中有这段代码用于调用 API 并将其加载到视图中:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! TableViewCell
    cell.nameLabel!.text = nameArray[indexPath.row]
    cell.dobLabel!.text = dobArray[indexPath.row]
    cell.descLabel!.text = descArray[indexPath.row]

    /*
    let imgURL = NSURL(string: imgURLArray[indexPath.row])
    let data = NSData(contentsOf: (imgURLArray as? URL)!)
    cell.imageView!.image = UIImage(data: data as! Data)
    */

    return  cell
}

这是我的 TableViewCell 文件:

class TableViewCell: UITableViewCell {

    @IBOutlet weak var nameLabel: UILabel?
    @IBOutlet weak var descLabel: UILabel?
    @IBOutlet weak var dobLabel: 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
    }
}

【问题讨论】:

  • 为什么要用cell.nameLabel!作为可选?你能分享自定义单元格文件吗?
  • 您是否创建了自定义 Cell 类?
  • 您使用! 强制取消引用您的选项,但如果嵌入了 nil,那么您取消引用 nil 指针。如果您觉得使用 ? 和 optional 是第一条基本规则,那么您更喜欢使用它。
  • 在哪一行?请不要让人们猜测,您是在寻求帮助,因此您有责任提供所有必要的信息。你检查了什么答案???
  • 天哪,不要使用 4 个单独的数组来存储 4 条相关数据的集合。制作一个包含 4 条数据的结构或对象,并且只有这些结构/对象的一个​​简单数组

标签: ios swift swift3


【解决方案1】:

尝试修改你的 ApiViewController 并检查我的代码然后看看会发生什么

 import UIKit

 class ApiViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
    final let urlString = "http://microblogging.wingnity.com/JSONParsingTutorial/jsonActors"
    var nameArray = [String]()
    var dobArray = [String]()
    var imgURLArray = [String]()
    var descArray = [String]()
     var actorarray = NSArray()
    @IBOutlet weak var tableView: UITableView!

    override func viewDidLoad() {
        super.viewDidLoad()

        self.downloadJsonWithURL()

        // Do any additional setup after loading the view, typically from a nib.
    }

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

 func downloadJsonWithURL() {
    let url = NSURL(string: urlString)
    URLSession.shared.dataTask(with: (url as? URL)!, completionHandler: {(data, response, error) -> Void in

        if let jsonObj = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? NSDictionary {
            print(jsonObj!.value(forKey: "actors")!)

            actorarray = jsonObj!.value(forKey: "actors") as? NSArray

            self.tableView.reloadData()

        }
    }).resume()
 }

    func downloadJsonWithTask(){
        let url = NSURL(string:urlString)
        var downloadTask = URLRequest(url: (url as? URL)!,cachePolicy:URLRequest.CachePolicy.reloadIgnoringCacheData,timeoutInterval:20)
        downloadTask.httpMethod = "GET"
        URLSession.shared.dataTask(with: downloadTask,completionHandler:{(data,response,error) -> Void in
            let jsonData = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments)
            print(jsonData!)
        })
    }

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

 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! TableViewCell

    let dic = self.actorarray[indexPath.row] as! NSDictionary


    cell.nameLabel!.text = dic.object(forKey: "name") as! String
    cell.dobLabel!.text = dic.object(forKey: "dob") as! String
    cell.descLabel!.text = dic.object(forKey: "image") as! String

    return  cell
 }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-11-20
    • 1970-01-01
    • 1970-01-01
    • 2019-10-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多