【发布时间】:2014-12-06 00:45:23
【问题描述】:
我正在开展一个帮助学习 Swift 的简单项目,但我遇到了一个我认为具有更深层次影响/学习机会的问题(试图从光明的一面看)。
高级问题是,当我使用 AlamoFire 发布 JSON 编码的参数时,EXC_BAD_ACCESS 错误很快出现在我设置参数之一的单独代码行中(特别是 CoreLocation Manager 的“didUpdateLocations”)。 .. 这是代码:
在 ViewController 中,我创建了一个可变字典:
var parameters = [String:AnyObject]()
并且,对于didUpdateLocations 事件,我将更新后的纬度/经度值分配给可变字典中的相应键。
class ViewController: UIViewController, CLLocationManagerDelegate {
let appDelegate = UIApplication.sharedApplication().delegate as AppDelegate
...
func locationManager(locManager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {
appDelegate.parameters["longitude"] = locManager.location.coordinate.longitude
appDelegate.parameters["latitude"] = locManager.location.coordinate.latitude
}
最后,我有一个 POST 到服务器的周期性函数(使用 NSTimer.scheduledTimerWithTimeInterval)。
func updatePost() {
println("POSTing update")
Alamofire.request(.POST, "http://server.co/endpoint",
parameters: appDelegate.parameters, encoding: .JSON)
}
如果我注释掉 Alamofire POST,一切都很好。 使用 POST,我在 didUpdateLocations 的第一行(设置了 longitude 键)的第一行收到 EXC_BAD_ACCESS 错误
我怀疑这与 Alamofire 的编码例程如何转换参数有关,但我不知道为什么它会出现在 didUpdateLocations 函数中而不是 Alamofire 调用本身中......
谁能提供任何见解?谢谢
【问题讨论】:
-
你为什么要把所有的东西都放在 AppDelegate 中?全局共享可变状态是 EXC_BAD_ACCESS 和其他所有权错误的秘诀。
-
这是我之前尝试过的一种保留形式,但很好。我刚刚将
parameters移动到 ViewController 中,同样的问题正在发生。