ios - 在通知中使用选择器的最佳做法是什么

标签 ios swift

<分区>

在 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)的一部分。

关于ios - 在通知中使用选择器的最佳做法是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44837567/

相关文章:

ios - 无法使用参数列表类型 int 调用 substringToIndex

ios - 以编程方式约束彼此相邻的 3 个 View

ios - 如何停止设备方向改变

ios - 我如何能够创建一个 tableViewCell 以按字母顺序显示按文本字段添加的文本?

objective-c - 当初始值设定项不是编译时常量时,在 Swift 中使用 C 宏

ios - 打开数组中包含的类型

快速结契约(Contract)步

uitableview - 是否可以在 UITableView (Swift) 中的一行中添加 2 行

objective-c - 如何从文件名不是 URL 一部分的 URL 下载文件(iOS/Cocoa SDK)

ios - 如何从相关表中过滤数据(解析)