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

时间:2016-08-11 07:12:54

标签: ios swift

我对此代码有疑问 -

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)

2 个答案:

答案 0 :(得分: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!
  }
}

答案 1 :(得分:0)

我可以看到你要从请求中解析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)")
}