selector 사용법이 좀 바뀌었는데 예전 사용법이 너무 많이 검색된다.
문자열을 메소드로 인식시키는 예전 방법이 error 유발 가능성은 더 크지만 유연한 사용법을 제시할 수 있어 더 좋았던 것 같다.
지금은 이런 식으로 사용하려면 어찌해야 하는지..
역시 스위프트 공홈에서 퍼왔다.
In Swift 2.1, code like the below would compile with no problems:
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.rightBarButtonItem =
UIBarButtonItem(barButtonSystemItem: .Add, target: self,
action: "addNewFireflyRefernce")
}
func addNewFireflyReference() {
gratuitousReferences.append("We should start dealing in black-market beagles.")
}
The code itself is syntactically sound, but the app will crash because the navigation bar button calls a method addNewFireflyRefernce()
— it’s missing one of the Es in “reference”. These kinds of simple typos could easily introduce bugs, so Swift 2.2 deprecates using strings for selectors and instead introduces new syntax: #selector
.
Using #selector
will check your code at compile time to make sure the method you want to call actually exists. Even better, if the method doesn’t exist, you’ll get a compile error: Xcode will refuse to build your app, thus banishing to oblivion another possible source of bugs.
Here is the previous code example rewritten using #selector
:
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.rightBarButtonItem =
UIBarButtonItem(barButtonSystemItem: .Add, target: self,
action: #selector(addNewFireflyRefernce))
}
func addNewFireflyReference() {
gratuitousReferences.append("Curse your sudden but inevitable betrayal!")
}
When that code is built, the compiler will send back the error “Use of unresolved identifier ‘addNewFireflyRefernce’” — shiny!
For more information, see the Swift Evolution proposal or read the swift-evolution-announce post detailing the rationale.