使用NSNotificationCenter通知的异常问题处理

发送通知的方法:

 NSNotificationCenter.defaultCenter().postNotificationName(tcpMessageReceivedNotification, object: self)

订阅通知的类:

import Foundation
class CmdUtil {
    func sendOneRequest(cmd: String) -> Message{
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "getResponse", name: tcpMessageReceivedNotification, object: nil)
        ...
        return message
    }

    @objc func getResponse(notification: NSNotification) {
        var responseMessage = socketSubject.messageReceived
        logger.debug(responseMessage?.toJsonString())
    }
}

在 代码1 那里会抛运行时异常:

2015-07-03 10:45:23.657 MeApp[2118:147521] *** NSForwarding: warning: object 0x7fb735091b60 of class 'MeApp.CmdUtil' does not implement methodSignatureForSelector: -- trouble ahead

是因为 methodSignatureForSelector 是一个 Objective-C 的方法. 默认情况下, swift 对象不能拥有它, 解决的方法有两种:

1.在方法前增加 @objc或 dynamic

Adding dynamic to the function signature makes calls to it get dispatched using the Objective-C runtime which avoids our error.

或者直接在类前面加也可以:

@objc class CmdUtil{
...
}

2.让该类继承NSObject, 并在 init() 中调用 super.init()

import Foundation
class CmdUtil : NSObject{
    override init() {
        super.init()
    }
    func sendOneRequest(cmd: String) -> Message{
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "getResponse", name: tcpMessageReceivedNotification, object: nil)
        ...        
        return message
    }
    //func getResponse(notification: NSNotification) {
    func getResponse() {
        var responseMessage = socketSubject.messageReceived
        // 获取到
        if let response = responseMessage as Message! {
            logger.debug("getResponse() : \(responseMessage?.toJsonString())")
        }
    }
}

解决了methodSignatureForSelector的问题, 还会抛另外一个异常:

2015-07-03 10:36:51.385 MeApp[1954:140458] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[MeApp.CmdUtil getResponse]: unrecognized selector sent to instance 0x7fc870e7f5d0'

原因是因为getResponse()的签名不对, 不应该有NSNotification的参数

2015-07-08 09:521