chevron-up bell reply instagram twitter2 feed3 finder search-25px-p0

Selector in Objc/Swift


In this short article you will know:

  • Selector in Objc
  • Selector in Swift
  • Passing value using Selector

Selector in Objc:
Selector is a concept of Objective-C Runtime, which allows to turn a method's name (NSString) into a SEL type. Basically you cand find @selectoreverywhere, such as adding a method to a view, NSNotification, etc.

The above code shows adding a right navigation button named Email Me on the top navigation controller, and the button has a method called onSendEmail which allow you to do something such as sending an email.

Selector in Swift:

Similar usage in Swift:

Two things need to be aware in Swift when using Selector:

1, private methods must conform with @objc

In the above swift code, if the onSendEmail is a private method, the compiler will pop up an error:

The reason is such a method is only available to Swift class itself, selector is a objective-c method. So it will recommend you to add @objc in front of the function name:

@objc private func onSendEmail(){ }

2, Another thing is when methods have parameters, you can call in two ways:

Passing value using Selector:

Say if we want to pass a string value to onSendEmail, what we do then? And of course, a global variable is one solution to this, but what else?

The answer is: customizing a UIBarButtonItem. In the customized UIBarButtonItem, create an attribute where you want to store value.

Same thing on Objective-C.



Make Your Comments