ios 如何在 swift 编程中解决这个 EXC_BAD_ACCESS(code=EXC_i386_GPFLT)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24837295/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to solve this EXC_BAD_ACCESS(code=EXC_i386_GPFLT )in swift programming
提问by user3541467
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
这是我的代码。得到这个 EXC_BAD_ACCESS(code=EXC_i386_GPFLT)。我不知道如何找到和解决请帮助我...应用程序在获取经度时崩溃
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)
回答by Ankit Sachan
Short answer:
简短的回答:
enable Zombies in the Scheme and it will enable a breakpoint and proper reason will be displayed in the logs
在Scheme中启用Zombies,它将启用断点并在日志中显示正确的原因
Technical reason:
技术原因:
You are trying to do something which in not allowed in the architecture refer this What's the meaning of exception code "EXC_I386_GPFLT"?
您正在尝试做一些架构中不允许的操作,请参阅此异常代码“EXC_I386_GPFLT”的含义是什么?
回答by Grimxn
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
您的问题是您正在执行的大多数操作都可以返回 nil,如果您尝试将其用作非 nil 值,这将使 Swift 崩溃。您需要明确测试是否为零。大锤的做法是
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 anyof the keys, at the end you may or may nothave a valid pair of coordinates. This is exactly what Optionals are for. Consider rewriting it as a function that returns an optional:
……不过这很丑陋。由于此例程可能会或可能不会找到任何键,因此最后您可能会或可能不会拥有一对有效的坐标。这正是 Optionals 的用途。考虑将其重写为返回可选的函数:
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 needthat 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!)
这将使用可选的链接(?
),以减轻测试,但我们必须在打破它geometry
,因为我们需要的是是一个数组,因为我们需要访问它的特定元素(和,当然,应该测试它不是一个空数组!)
p.s. - ironically, your test on error != nil
does nothing, as you did not send error
to the JSONObjectWithData routine.
ps - 具有讽刺意味的是,您的测试error != nil
没有做任何事情,因为您没有发送error
到 JSONObjectWithData 例程。
回答by saraman
In that type of situation you can convert latitude to string. Updated code:
在这种情况下,您可以将纬度转换为字符串。更新代码:
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=NSString(format:mapServerResultArray.objectAtIndex(0).valueForKey("geometry").valueForKey("location").valueForKey("lng"))
var latitud :NSString
latitud=NSString(format:(mapServerResultArray .objectAtIndex(0).valueForKey("geometry").valueForKey("location").valueForKey("lat")))
placeName=NSString(format:mapServerResultArray .objectAtIndex(0).valueForKey("formatted_address"))
var longitude:Float=longitud.floatValue
var latitude:Float=latitud.floatValue
self.zoomMapAndCenterAtLatitude(latitude)
self.zoomMapAndCenterAtLongitud(longitude)
回答by Kinjal Dhagat
This response you are getting :"http://maps.googleapis.com/maps/api/geocode/json?address=Hyderabad,india"
您收到的此回复:“ http://maps.googleapis.com/maps/api/geocode/json?address=Hyderabad,india”
You can fetch like below:
你可以像下面这样获取:
Here jsondict is your respnse from api
这里 jsondict 是你对 api 的响应
NSArray *results = [jsonDict objectForKey:@"results"];
NSDictionary *geometry = [[results objectAtIndex:0] valueForKey:@"geometry"];
NSArray *location = [geometry objectForKey:@"location"];
float lat = [[location valueForKey:@"lat"] floatValue];
float lng = [[location valueForKey:@"lng"] floatValue];
回答by Kinjal Dhagat
use this :
用这个 :
var longitud:NSString =(mapServerResultArray.objectAtIndex(0).valueForKey("geometry").objectForKey("location").valueForKey("lng")) as NSString
var latitud :NSString =
(mapServerResultArray .objectAtIndex(0).valueForKey("geometry").objectForKey("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)