添加具有选择器功能的观察者时 NotificationCenter 抛出错误
NotificationCenter throw error when adding observer with selector function
在服务器端,我使用 socket.io 库在用户输入他们的设备时发送一些 JS 对象数据类型:
var typingUsers = {};
clientSocket.on("startType", function(clientNickname){
typingUsers[clientNickname] = 1;
io.emit("userTypingUpdate", typingUsers);
});
当应用收到数据时,它会post通知:
private func listenForOtherMessages() {
socket.on("userTypingUpdate") { (dataArray, socketAck) -> Void in
NotificationCenter.default.post(name:NSNotification.Name(rawValue: "userTypingNotification"), object: dataArray[0] as! [String: AnyObject])
}
}
然后将通知作为观察者添加到视图控制器:
NotificationCenter.default.addObserver(self, selector: Selector(("handleDisconnectedUserUpdateNotification:")), name: NSNotification.Name(rawValue: "userWasDisconnectedNotification"), object: nil)
此实现总是抛出错误"unrecognised selector send to ..."
但是下面没有选择器的实现工作正常:
NotificationCenter.default.addObserver(forName:NSNotification.Name(rawValue: "userTypingNotification"), object: nil, queue: nil){ object in
print(object)
}
看来我无法为观察者添加选择器,我认为问题可能出在对象数据类型上,但我无法弄清楚为什么..
找到答案:
NotificationCenter.default.addObserver(self, selector: #selector(self.userTypingNotification), name: NSNotification.Name(rawValue: "userWasDisconnectedNotification"), object: nil)
在服务器端,我使用 socket.io 库在用户输入他们的设备时发送一些 JS 对象数据类型:
var typingUsers = {};
clientSocket.on("startType", function(clientNickname){
typingUsers[clientNickname] = 1;
io.emit("userTypingUpdate", typingUsers);
});
当应用收到数据时,它会post通知:
private func listenForOtherMessages() {
socket.on("userTypingUpdate") { (dataArray, socketAck) -> Void in
NotificationCenter.default.post(name:NSNotification.Name(rawValue: "userTypingNotification"), object: dataArray[0] as! [String: AnyObject])
}
}
然后将通知作为观察者添加到视图控制器:
NotificationCenter.default.addObserver(self, selector: Selector(("handleDisconnectedUserUpdateNotification:")), name: NSNotification.Name(rawValue: "userWasDisconnectedNotification"), object: nil)
此实现总是抛出错误"unrecognised selector send to ..."
但是下面没有选择器的实现工作正常:
NotificationCenter.default.addObserver(forName:NSNotification.Name(rawValue: "userTypingNotification"), object: nil, queue: nil){ object in
print(object)
}
看来我无法为观察者添加选择器,我认为问题可能出在对象数据类型上,但我无法弄清楚为什么..
找到答案:
NotificationCenter.default.addObserver(self, selector: #selector(self.userTypingNotification), name: NSNotification.Name(rawValue: "userWasDisconnectedNotification"), object: nil)