【问题标题】:error - thread 1 exc_bad_instruction (code=exc_1386_invop subcode=0x0)错误 - 线程 1 exc_bad_instruction(代码=exc_1386_invop 子代码=0x0)
【发布时间】:2016-08-11 07:12:53
【问题描述】:

我对这段代码有疑问 -

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


func get(){
    let url = NSURL(string: "http://www..php")
    let data = NSData(contentsOfURL: url!)
    values = try! NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as!NSArray

    tableView.reloadData()
}

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

这个错误 线程 1 exc_bad_instruction (code=exc_1386_invop subcode=0x0)

【问题讨论】:

  • 您能否分享您的数据,以便更好地理解。
  • @Anupam Mishra - func get(){ let url = NSURL(string: ".php") let data = NSData(contentsOfURL: url!) values = try!NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as!NSArray tableView.reloadData() } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return values.count; }
  • 请在原帖中添加您的代码并格式化(cmd+k)。
  • 删除感叹号并捕获/处理错误。
  • @jbehrens94 我添加更多代码

标签: ios swift


【解决方案1】:

试试这个 -

func get()
{
if let url = NSURL(string: "https://www.hackingwithswift.com") {
    do {

        let JSONData = NSData(contentsOfURL: url)
        do {
            let JSON = try NSJSONSerialization.JSONObjectWithData(JSONData!, options:NSJSONReadingOptions(rawValue: 0))
            guard let JSONDictionary :NSDictionary = JSON as? NSDictionary else {
                print("Not a Dictionary")
                // put in function
                return
            }
            print("JSONDictionary! \(JSONDictionary)")
        }
        catch let JSONError as NSError {
            print("\(JSONError)")
        }
    } catch {
        // contents could not be loaded
    }
}
else
   {
    // the URL was bad!
  }
}

【讨论】:

    【解决方案2】:

    如我所见,您将从请求中解析 JSON。

    尝试使用我的建议。

    首先不要使用try!,尝试正确处理异常是不好的做法。

    //Catch error if it is son error.
    do {
        //Parse JSON and handle exception.
        let JSON = try NSJSONSerialization.JSONObjectWithData(data, options:NSJSONReadingOptions(rawValue: 0))
        guard let JSONDictionary :NSDictionary = JSON as? NSDictionary else {
            print("Not a Dictionary")
            return
        }
        print("JSONDictionary! \(JSONDictionary)")
    }
    catch let JSONError as NSError {
        print("\(JSONError)")
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多