简体   繁体   English

如何在Swift4中修复NotificationCenter

[英]How to fix NotificationCenter in swift4

During conversion from swift3 to swift4 the convertor has changed NotificationCenter to the following view: 在从swift3转换为swift4的过程中,转换器将NotificationCenter更改为以下视图:

 NotificationCenter.default.addObserver(self, selector: #selector(myController.myFunction(_:)), name: NSNotification.Name.NSTextView.didChangeSelectionNotification, object: myNSTextView)

So, because of selector in .addObserver() myFunction now has @objc in front. 因此,由于.addObserver()selector ,myFunction现在前面带有@objc。 Now the compiler is complaining, that the type NSNotification.Name has no member NSTextView . 现在,编译器在抱怨类型NSNotification.Name没有成员NSTextView This is what convertor made, not me. 这是转换器制造的,不是我制造的。 I am confused. 我很困惑。

How to fix this ? 如何解决呢?

Update . 更新 I have found the information here How to migrate NSWorkspace notifications to Swift 4? 我在这里找到了信息如何将NSWorkspace通知迁移到Swift 4?

So I have to use 所以我必须使用

NotificationCenter.default.addObserver(self, selector: #selector(myController.myFunction(_:)), name: NSTextView.didChangeSelectionNotification, object: myNSTextView)  

As mentioned in Gary's comment, you need to switch over from calling the Selector , and instead use a callback. 正如Gary的评论中所述,您需要从调用Selector切换到,而是使用回调。 The following example shows what you need to setup for this to work. 以下示例显示了进行此设置所需的设置。

var didBecomeActive: (Notification) -> Void = { notification in
    print("app became active")
}

private func setupNotification() {
    NotificationCenter.default.addObserver(forName: .UIApplicationDidBecomeActive,
                                           object: nil,
                                           queue: OperationQueue.main,
                                           using: didBecomeActive)
}

First, I create the var didBecomeActive , and made it a type of (Notification) -> Void to comply with what the function expects. 首先,创建var didBecomeActive ,并使其成为(Notification) -> Void一种类型,以符合该函数的期望。 In my example, I left the notification value in the callback, but if you are not using it, you can replace it with a _ and it will work fine. 在我的示例中,我将notification值留在了回调函数中,但是如果您不使用它,则可以将其替换为_ ,它将正常工作。

Next, instead of calling the function you use: 接下来,不用调用您使用的函数:

NotificationCenter.default.addObserver(self, selector: #selector(myController.myFunction(_:)), name: NSTextView.didChangeSelectionNotification, object: myNSTextView)  

I call the following instead: 我称之为以下内容:

NotificationCenter.default.addObserver(forName: <#T##NSNotification.Name?#>, 
    object: <#T##Any?#>, 
    queue: <#T##OperationQueue?#>, 
    using: <#T##(Notification) -> Void#>)

For the using param, just provide the variable you set up to receive the callback, which in this case is didBecomeActive . 对于using参数,只需提供您设置为接收回调的变量,在本例中为didBecomeActive

您也可以在方法之前输入@objc,它将起作用

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM