Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use #selector instead of explicitly constructing a Selector [duplicate]

Tags:

xcode

swift

In the following snippet, what is the reason why Xcode recommend "Use #selector instead of explicitly constructing a Selector"?

// addButton = UIBarButtonItem.init(barButtonSystemItem: UIBarButtonSystemItem.Add, 
//             target: self, action: #selector(FoldersMaintenanceVC.addButtonPressed))
addButton = UIBarButtonItem.init(barButtonSystemItem: UIBarButtonSystemItem.Add, 
            target: self, action: Selector("addButtonPressed"))

self.navigationItem.leftBarButtonItem = addButton

func addButtonPressed()
{
    myNslogSys2(self, funcName:#function)
}
like image 882
user523234 Avatar asked Mar 24 '16 15:03

user523234


People also ask

Whats a better word for use?

The words employ and utilize are common synonyms of use.

What did mean by use?

1 : to put into action or service : avail oneself of : employ. 2 : to expend or consume by putting to use —often used with up. 3 : stand sense 1d the house could use a coat of paint.

Is use word verb?

verb (used with object), used, us·ing. to employ for some purpose; put into service; make use of: to use a knife.


3 Answers

It recommends that you use the Swift 2.2 new #selector because it is more type-safe since you cannot make a selector reference to a non-existing method whereas with Selector(String), you could reference a non-existing one.

like image 156
Valentin Avatar answered Dec 05 '22 23:12

Valentin


Using #selector is now the correct way in Swift to reference a selector. Use of the struct Selector and string literals for selectors, such as "mySel:" have been deprecated.

The new #selector is now type safe and allows for compiler checking and autocompletion of the selector that you're passing in. This fixes the very common mistake of a spelling mistake in your selector (in the case of string literals)

like image 40
Chris Avatar answered Dec 05 '22 23:12

Chris


It happens cause now construction of Selector from string literals deprecated and will be removed in Swift 3.0

With the introduction of the #selector syntax, we should deprecate the use of string literals to form selectors. Ideally, we could perform the deprecation in Swift 2.2 and remove the syntax entirely from Swift 3.

You can read more details about this change here https://github.com/apple/swift-evolution/blob/master/proposals/0022-objc-selectors.md

like image 26
Peter K Avatar answered Dec 06 '22 00:12

Peter K