在 Swift 3 中,要注册通知,我可以通过以下方式进行:
NotificationCenter.default.addObserver(self, selector: #selector(ViewController.n1(notification:)), name: Notification.Name("123"), object: nil)
func n1(notification: Notification){
print("123")
}
// #selector is more brief
NotificationCenter.default.addObserver(self, selector: #selector(n2), name: Notification.Name("456"), object: nil)
func n2(notification: Notification){
print("456")
}
但是,在Xcode 9.0 beta 2(Swift 4.0)中,当我以这种方式注册通知时,对象方法应该有一个前缀@objc
,为什么?使用通知的最佳做法是什么?
“#selector”的参数引用了未暴露给 Objective-C 的实例方法“n1(notification:)”
//Add '@objc' to expose this instance method to Objective-C
@objc func n1(notification: Notification){
print("123")
}
@objc func n2(notification: Notification){
print("456")
}
你没有看错。
事实上,苹果是这样解释你应该在 Swift 4 中使用选择器的:
In Objective-C, a selector is a type that refers to the name of an
Objective-C method. In Swift, Objective-C selectors are represented by
the Selector structure, and can be constructed using the #selector
expression. To create a selector for a method that can be called from
Objective-C, pass the name of the method, such as #selector(MyViewController.tappedButton(sender:)). To construct a selector for a property’s Objective-C getter or setter method, pass
the property name prefixed by the getter: or setter: label, such as #selector(getter: MyViewController.myButton).
文档链接 here .
为了回答您关于为什么的问题,well 选择器实际上是一种在 cocoa 类之间发送消息的方式,而不是 swift 功能。所以它们实际上是基于 Objective-C 的,因此你需要保持它们之间的兼容性。
选择器:
A selector is the name used to select a method to execute for an
object, or the unique identifier that replaces the name when the
source code is compiled. A selector by itself doesn’t do anything. It
simply identifies a method. The only thing that makes the selector
method name different from a plain string is that the compiler makes
sure that selectors are unique. What makes a selector useful is that
(in conjunction with the runtime) it acts like a dynamic function
pointer that, for a given name, automatically points to the
implementation of a method appropriate for whichever class it’s used
with.
您可以阅读更多关于选择器的信息 here .
但基本上,它们只是 cocoa 使用的“消息”接口(interface)的一部分。