【问题标题】:What is the best practice to use selector in Notification [duplicate]在通知中使用选择器的最佳做法是什么[重复]
【发布时间】:2017-06-30 02:09:54
【问题描述】:

在 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,为什么?使用通知的最佳做法是什么?

Argument of '#selector' refers to instance method 'n1(notification:)' that is not exposed to Objective-C

//Add '@objc' to expose this instance method to Objective-C
@objc func n1(notification: Notification){
    print("123")
}

@objc func n2(notification: Notification){
    print("456")
}

【问题讨论】:

    标签: ios swift


    【解决方案1】:

    你没有错。

    事实上,这就是苹果解释你应该在 Swift 4 中使用选择器的方式:

    在 Objective-C 中,选择器是一种引用对象名称的类型 Objective-C 方法。在 Swift 中,Objective-C 选择器由 Selector 结构,可以使用#selector 构造 表达。为可以调用的方法创建选择器 Objective-C,传递方法的名字,比如#selector(MyViewController.tappedButton(sender:))。要为属性的 Objective-C getter 或 setter 方法构造选择器,请通过 以 getter: 或 setter: 标签为前缀的属性名称,例如 #selector(getter: MyViewController.myButton)。

    文档链接here

    为了回答你关于为什么的问题,井选择器实际上是一种在可可类之间发送消息的方式,而不是一个快速的功能。所以它们实际上是基于 Objective-C 的,所以你需要保持它们之间的兼容性。

    选择器:

    选择器是用于选择要执行的方法的名称 对象,或替换名称时的唯一标识符 源代码已编译。选择器本身不做任何事情。它 只是标识一种方法。唯一使选择器 与普通字符串不同的方法名称是编译器使 确保选择器是唯一的。使选择器有用的是 (与运行时一起)它就像一个动态函数 指针,对于给定的名称,自动指向 实现适用于所使用的任何类的方法 与。

    您可以阅读有关选择器的更多信息here

    但基本上,它们只是 cocoa 使用的“消息”界面的一部分。

    【讨论】:

      猜你喜欢
      • 2020-08-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多