如何在swift编程中解决这个EXC_BAD_ACCESS(code = EXC_i386_GPFLT) [英] How to solve this EXC_BAD_ACCESS(code=EXC_i386_GPFLT )in swift programming

查看:214
本文介绍了如何在swift编程中解决这个EXC_BAD_ACCESS(code = EXC_i386_GPFLT)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的code.getting这个EXC_BAD_ACCESS(代码= EXC_i386_GPFLT)我不知道如何找到和解决plz帮助我...应用程序得到崩溃时获得经度

this is my code.getting this EXC_BAD_ACCESS(code=EXC_i386_GPFLT).I don'n know how to find and solve plz help me ...application getting crash when get longitude

mapServerRequest="Hyderabad,india"
var mapAddress:NSString=mapServerRequest
mapAddress.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLPathAllowedCharacterSet())
     println(mapAddress)
var urlpath=NSString(format: "http://maps.googleapis.com/maps/api/geocode/json?address=%@", mapAddress)
     println(urlpath)
var url = NSURL.URLWithString(urlpath)
    println(url)
var jsonData:NSData=NSData(contentsOfURL:url)

       if(jsonData != nil)
    {
        var error:NSError=NSError(coder: nil)
        var result:NSDictionary=NSJSONSerialization .JSONObjectWithData(jsonData, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary
        //println(result)
        if (error != nil)
        {
            mapServerResultArray=result.valueForKey("results") as NSMutableArray
           // println(mapServerResultArray)

        }
      var longitud:NSString

           longitud=mapServerResultArray.objectAtIndex(0).valueForKey("geometry").valueForKey("location").valueForKey("lng")as NSString

        var latitud :NSString = (mapServerResultArray .objectAtIndex(0).valueForKey("geometry").valueForKey("location").valueForKey("lat")) as NSString
        placeName=mapServerResultArray .objectAtIndex(0).valueForKey("formatted_address") as NSString
        var longitude:Float=longitud.floatValue
        var latitude:Float=latitud.floatValue
        self.zoomMapAndCenterAtLatitude(latitude)
        self.zoomMapAndCenterAtLongitud(longitude) 


推荐答案

您的问题是,您所执行的大多数操作都可以返回nil,将cr如果您尝试将其用作非零值,则为灰色Swift。你需要明确的测试为零。大锤的做法是

Your problem here is that most of the operations you are performing can return nil, which will crash Swift if you try and use it as a non-nil value. You need to be explicit about testing for nil. The sledgehammer way of doing it would be

let mapAddress = "Hyderabad,india"

let url = NSURL.URLWithString("http://maps.googleapis.com/maps/api/geocode/json?address=\(mapAddress)")

let jsonData = NSData(contentsOfURL:url)

var latitude = NSNumber(double: 0.0)
var longitude = NSNumber(double: 0.0)
var success = false

if jsonData != nil {
    if let result = NSJSONSerialization.JSONObjectWithData(jsonData, options: NSJSONReadingOptions.MutableContainers, error: nil) as? NSDictionary {
        if let mapServerResultArray = result.valueForKey("results") as? NSArray {
            if let geometry = mapServerResultArray[0].valueForKey("geometry") as? NSDictionary {
                if let location = geometry.valueForKey("location") as? NSDictionary {
                    if let lat = location.valueForKey("lat") as? Float {
                        latitude = lat
                        if let lng = location.valueForKey("lng") as? Float {
                            longitude = lng
                            success = true
                        }
                    }
                }
            }
        }
    }
}
if success {
    println("Latitude = \(latitude), longitude=\(longitude)")
} else {
    println("Failed")
}

...但是这是丑陋的。由于此例程可能找到或可能找不到任何的密钥,所以您最终可能有也可能不具有一对有效的坐标。这正是可选的。考虑重写它作为返回可选的函数:

... however that is ugly. As this routine may or may not find any of the keys, at the end you may or may not have a valid pair of coordinates. This is exactly what Optionals are for. Consider rewriting it as a function that returns an optional:

struct Coordinate { // Or use any of Cocoa's similar structs
    var latitude: Double
    var longitude: Double
}

func getCoordsOf(#address: String) -> Coordinate? {
    let url = NSURL.URLWithString("http://maps.googleapis.com/maps/api/geocode/json?address=\(address)")
    let jsonData = NSData(contentsOfURL:url)
    if jsonData == nil { return nil }

    let result = NSJSONSerialization.JSONObjectWithData(jsonData, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary
    if result == nil { return nil }

    if let geometry = result.valueForKey("results").valueForKey("geometry") as? NSArray {
        if geometry.count > 0 {
            let lat = geometry[0].valueForKey("location")?.valueForKey("lat")?.doubleValue
            let lng = geometry[0].valueForKey("location")?.valueForKey("lng")?.doubleValue

            if (lat != nil) && (lng != nil) {
                return Coordinate(latitude: lat!, longitude: lng!)
            }
        }
    }
    return nil
}

if let coord = getCoordsOf(address: "Hyderabad,india") {
    // ... do something
}

这使用可选链接()来减少测试,但是我们必须打破它几何因为我们需要是一个数组,因为我们需要访问它的一个特定元素(当然,应该测试它不是一个空数组!)

This uses Optional Chaining (?) to lessen the testing, but we have to break it at geometry because we need that to be an array, as we need to access a specific element of it (and, of course, should test that it isn't an empty array!)

ps - 讽刺的是,您对错误!= nil 的测试不执行任何操作,因为您没有向JSONObjectWithData例程发送错误

p.s. - ironically, your test on error != nil does nothing, as you did not send error to the JSONObjectWithData routine.

这篇关于如何在swift编程中解决这个EXC_BAD_ACCESS(code = EXC_i386_GPFLT)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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