I'm trying to fix my NSNotificationCenter and its not working
the message :
'Use of string literal for Objective-C selectors is deprecated; use '#selector' instead'.
the line :
NSNotificationCenter.defaultCenter().addObserver(self, Selector :#selector(GameViewController.goBack)(GameViewController.goBack), object: nil)
self.dismissViewControllerAnimated(true, completion: {
});
}
In Swift, Objective-C selectors are represented by the Selector structure, and you create them using the #selector expression. In Swift, you create a selector for an Objective-C method by placing the name of the method within the #selector expression: #selector(MyViewController. tappedButton(_:)) .
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.
Sends a specified message to the receiver and returns the result of the message. iOS 2.0+ iPadOS 2.0+ macOS 10.0+ Mac Catalyst 13.0+ tvOS 9.0+ watchOS 2.0+ Required.
@Eendje's answer is incorrect by its first comment.
I think it is better answer.
NSNotificationCenter.defaultCenter().addObserver(self, #selector(self.goBack), name: "your notification name", object: nil)
If some actions has target, it should be presented like #selector(target.method)
or #selector(target.method(_:))
Here is another example
UIGestureRecognizer(target: target action:#selector(target.handleGesture(_:))
The code you pasted doesn't make any sense:
Selector :#selector(GameViewController.goBack)(GameViewController.goBack) // ???
It should be:
NSNotificationCenter.defaultCenter().addObserver(self, #selector(goBack), name: "your notification name", object: nil)
You have to look at this: https://github.com/apple/swift-evolution/blob/master/proposals/0022-objc-selectors.md
The #selector
proposal was made in conjunction with another proposal, specifying swift functions by their argument labels. So if I have a struct:
struct Thing
func doThis(this: Int, withOtherThing otherThing: Int) {
}
}
I would reference that function like:
let thing = Thing()
thing.doThis(_:withOtherThing:)
Remember here I'm referencing the function itself, not calling it.
You would use that with #selector:
#selector(self.doThis(_:withOtherThing:)
Function with no arguments:
#selector(self.myFunction)
Function with one implicit argument:
#selector(self.myOtherFunction(_:))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With