快速关闭中的BAD_INSTRUCTION

时间:2014-06-04 14:49:06

标签: closures swift

func loadMe() -> Void {
    println(me.initUrl());

    let url:NSURL = NSURL(string:me.initUrl())
    let request:NSURLRequest = NSURLRequest(URL:url)
    let queue:NSOperationQueue = NSOperationQueue()

    NSURLConnection.sendAsynchronousRequest(request, queue:queue, completionHandler:{response, data, error in
        if data {
            var jerr:NSError?
            var json:NSDictionary = NSJSONSerialization.JSONObjectWithData(data, options:NSJSONReadingOptions.MutableContainers, error:&jerr) as NSDictionary

            if !jerr {
                println(json.description)
                let time:String = json.valueForKey("time") as String
                println(time)

                //  self.me.setDictionary(json)
            }
        }
    })
}

上面的代码工作正常,我希望将NSDictionary中的值赋给变量。

let time:String = json.valueForKey("time") as String 

之后是EXC_BAD_INSTRUCTION(代码= EXC_I386_INVOP,子代码= 0x0)但是

println(json.description) 

打印出有效的NSDictionary。有人知道这个问题的解决方案吗?

2 个答案:

答案 0 :(得分:2)

valueForKey()方法返回一个可选值;你正在强制该值为一个字符串,显然是导致崩溃。我可以让Swift REPL崩溃:

  1> var json = ["a": "1", "b": "2"]
json: Dictionary<String, String> = {
  [0] = {
    key = "a"
    value = "1"
  }
  [1] = {
    key = "b"
    value = "2"
  }
}
  2> let data:String = json["b"] as String
Bitcast requires both operands to be pointer or neither
  %58 = bitcast i8* %57 to %SS.232
Bitcast requires both operands to be pointer or neither
  %110 = bitcast i8* %109 to %SS.232
Stored value type does not match pointer operand type!
  store %SS.232 %110, i8** %.core7._baseAddress.value, align 8
 i8*LLVM ERROR: Broken function found, compilation aborted!
Assertion failed: (err == 0), function ~Mutex, file /SourceCache/lldb_KLONDIKE/lldb_KLONDIKE-320.3.100/source/Host/common/Mutex.cpp, line 246.
Abort trap: 6

解决方案是放弃字符串强制。在我的例子中:

  2> let data:String? = json["b"]
data: String? = "2"

  3> let data:String? = json["c"]
data: String? = nil

我怀疑你添加了&#39;作为字符串&#39; 1)知道该值实际上是一个String,2)以避免编译器错误。正确的方法是使用?来表示可选值。

答案 1 :(得分:2)

在我意识到并非NSDictionary的所有值都是NSStrings之后,我解决了我的问题,即转换为原始NSDictionary值的正确类型。如果您的服务返回类似这样的混合类型JSON对象

{"id":2, "name":"AC Vent Temp", ...}

你必须获取它的价值。

var id:int = sensor.valueForKey("id") as Int;
var name:String? = sensor.valueForKey("name") as String;