BAD_INSTRUCTION在swift闭包 [英] BAD_INSTRUCTION within swift closure

查看:117
本文介绍了BAD_INSTRUCTION在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分配给变量。

The code above works fine up to the point where i want to assign a value from an NSDictionary to a variable.

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

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

is followed by EXC_BAD_INSTRUCTION(code=EXC_I386_INVOP,subcode=0x0) but

println(json.description) 

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

prints out a valid NSDictionary. Does anybody know a solution to this problem?

推荐答案

我解决了我的问题,转换到正确的类型的原始NSDictionary值后我意识到不是NSDictionary的所有值都是NSStrings。如果您的服务返回类似于此的混合类型JSON对象

I solved my problem with casting to the correct type of the original NSDictionary value after i realised that not all values of the NSDictionary were NSStrings. If your service returns a mixed type JSON object like this

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

你必须获取这样的值。

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

这篇关于BAD_INSTRUCTION在swift闭包的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆