我添加了Swift的新功能到Objective应用程序。
我在目标C(登记)中有一位观察员:
[[NSNotificationCenter defaultCenter] removeObserver:self name:NOTIFICATION_SERVER_SENT_CONFIRMATION_SMS object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(confirmSms) name:NOTIFICATION_SERVER_SENT_CONFIRMATION_SMS object:nil];并以确认方式:
[[NSNotificationCenter defaultCenter] postNotificationName:NOTIFICATION_SERVER_SENT_CONFIRMATION_SMS object:nil];如何在Swift中观察这一点?我试过了
NotificationCenter.default.removeObserver(self,
name: NOTIFICATION_SERVER_SENT_CONFIRMATION_SMS,
object:nil);
NotificationCenter.default.addObserver(self,
selector:#selector(self.confirmationSmsSent),
name: NOTIFICATION_SERVER_SENT_CONFIRMATION_SMS,
object: nil);我得到了
未解析标识符“NOTIFICATION_SERVER_SENT_CONFIRMATION_SMS”的使用
谢谢
//编辑:
我已在Obj-C中声明:
NSString *const NOTIFICATION_SERVER_SENT_CONFIRMATION_SMS = @"confirmationSMSSent";这个还能用吗?
let name: NSNotification.Name = NSNotification.Name("Your_Notification_Name_Key_String") //NOTIFICATION_SERVER_SENT_CONFIRMATION_SMS当我用
NotificationCenter.default.addObserver(self, selector:#selector(self.confirmationSmsSent(_:)), name: name, object: nil)
func confirmationSmsSent(notification: NSNotification) {
}我搞错了
类型'MyController‘的值没有成员'confirmationSmsSent’
在……上面
selector:#selector(self.confirmationSmsSent(_:)),名称:名称,对象:0)
发布于 2017-02-03 08:30:10
在Swift 3中,语法发生了变化。您必须定义NSNotification.Name的变量
let name: NSNotification.Name = NSNotification.Name("Your_Notification_Name_Key_String") //NOTIFICATION_SERVER_SENT_CONFIRMATION_SMS
//Add Notification
NotificationCenter.default.addObserver(self, selector:#selector(self.yourSelector(_:)), name: name, object: nil)
//Remove Notification Observer
NotificationCenter.default.removeObserver(self, name: name, object: nil)
//Your Selector
func yourSelector(_ notification: Notification) {
//Code
}发布于 2017-02-03 08:28:31
这是因为您还没有声明NOTIFICATION_SERVER_SENT_CONFIRMATION_SMS。
通常通知名称只是一个字符串,顺便说一句,您必须将其转换为嵌套的NSNotification.Name类型。
let NOTIFICATION_SERVER_SENT_CONFIRMATION_SMS = NSNotification.Name("<some string>")发布于 2017-02-03 08:36:32
最有用的迅捷代码是扩展。
extension Notification.Name {
static let someNewName = "ThatsItImAwsome"
} 内帖使用情况:
.someNewKey
这是:
NotificationCenter.default.addObserver(self, selector:#selector(self.yourSelector(_:)), name: .someNewKey, object: nil)https://stackoverflow.com/questions/42019788
复制相似问题