0

During conversion from swift3 to swift4 the convertor has changed NotificationCenter to the following view:

 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. Now the compiler is complaining, that the type NSNotification.Name has no member 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?

So I have to use

NotificationCenter.default.addObserver(self, selector: #selector(myController.myFunction(_:)), name: NSTextView.didChangeSelectionNotification, object: myNSTextView)  
CodeBender
  • 35,668
  • 12
  • 125
  • 132
VYT
  • 1,071
  • 19
  • 35
  • Watch the WWDC video “What’s New In Foundation” for information about the key paths implementation in Swift and how you can do observation with blocks/closures instead of callbacks. https://developer.apple.com/videos/play/wwdc2017/212/ – Gary Makin Jun 15 '17 at 23:44

2 Answers2

1

As mentioned in Gary's comment, you need to switch over from calling the Selector, and instead use a callback. 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. 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.

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.

CodeBender
  • 35,668
  • 12
  • 125
  • 132
0

you may also type @objc before method and it will work

Amr Angry
  • 3,711
  • 1
  • 45
  • 37