【问题标题】:Why postNotification fail in the second call in Swift?为什么 postNotification 在 Swift 的第二次调用中失败?
【发布时间】:2016-04-21 02:03:48
【问题描述】:

首先我从 locationManager 调用一个方法来更新位置(didUpdateLocations)。 在这种方法中,我使用 postNotification 并且一切正常。 但是当我第二次从 locationManager 调用该方法时,出现一个错误,“由于未捕获的异常 'NSInvalidArgumentException' 而终止应用程序,原因:'-[NSMallocBlock sendMessageNotification:]:无法识别的选择器已发送到实例0x17026fac0'"

[信息变量错误]

func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    debugLog("locations \(locations)")

    if let location = locations.last {

        let mMessage = Message()
        mMessage.latitude = location.coordinate.latitude
        mMessage.longitude = location.coordinate.longitude
        let userInfo = ["message": JSONSerializer.toJson(mMessage)]

        if !userInfo.isEmpty {
            NSNotificationCenter.defaultCenter().postNotificationName("__SEND_MESSAGE__",
                object: nil,
                userInfo: userInfo)
        }


    }

【问题讨论】:

  • 请显示您的代码和堆栈跟踪,但看起来您正在以某种方式引用已释放的内存。
  • 我添加了该方法,但在堆栈跟踪中只说由于未捕获的异常 'NSInvalidArgumentException' 而终止应用程序,原因:'-[NSMallocBlock sendMessageNotification:]:无法识别的选择器发送到实例 0x17026fac0'
  • 为什么要将对象序列化为 JSON?您可以将 Message 对象添加到字典中。事实上,你可以只添加 location 或 location.coordinate 对象
  • 问题是我将 Json 数据发送到服务器。
  • 那么你应该在发送到服务器之前转换成 JSON。在这里做是没有意义的。无论如何,这段代码应该没有理由导致崩溃。您需要查看堆栈跟踪以查看它在您的代码中尝试调用该函数的位置sendMessageNotification

标签: ios swift cllocationmanager nsnotificationcenter


【解决方案1】:

在我添加通知的同一个类中,我的代码中缺少一个删除观察者。

deinit {
    // perform the deinitialization
    NSNotificationCenter.defaultCenter().removeObserver(self)
}

谢谢。

【讨论】:

    猜你喜欢
    • 2019-09-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-13
    • 2021-04-02
    • 2010-12-21
    • 1970-01-01
    相关资源
    最近更新 更多