What is the best practice for using a selector in a notification

In Swift 3, to register a notification, I can do the following:

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")
}

However, in Xcode 9.0 beta 2 (Swift 4.0), when I register a notification this way, the object method must have a prefix @objc, why? What is the best practice for using Notices?

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")
}
+4
source share
1 answer

You are not mistaken.

This is actually how Apple explains that you should use selectors in Swift 4:

Objective-C - , Objective-C. Swift Objective-C Selector, #selector . , Objective-C, , #selector (MyViewController.tappedButton(sender:)). Objective-C getter setter, , : setter: label, #selector (getter: MyViewController.myButton).

.

, cocoa, . Objective-C, .

:

- , , , , . . . , , , , . , , ( ) , , .

.

, cocoa.

+3

Source: https://habr.com/ru/post/1680458/


All Articles