Objective-C观察者 - 如何在Swift中使用

时间:2017-02-03 08:25:10

标签: ios objective-c swift swift3

我正在使用Swift向Objective-C app添加新功能。

我在Objective-C(registration.m)中有这个观察者:

[[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];

并在confirm.m中:

[[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'

on

  

NotificationCenter.default.addObserver(self,selector:#selector(self.confirmationSmsSent(_ :)),name:name,object:nil)

3 个答案:

答案 0 :(得分:3)

在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
}

答案 1 :(得分:1)

这是因为您尚未声明NOTIFICATION_SERVER_SENT_CONFIRMATION_SMS。

通常,通知名称只是一个字符串,顺便说一句,您必须将其强制转换为嵌套的NSNotification.Name类型。

let NOTIFICATION_SERVER_SENT_CONFIRMATION_SMS = NSNotification.Name("<some string>")

答案 2 :(得分:1)

最有用的swift - lije代码是扩展名

extension Notification.Name {
static let someNewName = "ThatsItImAwsome" 
} 

帖子内的用法:

.someNewKey

这样:

NotificationCenter.default.addObserver(self, selector:#selector(self.yourSelector(_:)), name: .someNewKey, object: nil)