Reputation: 16758
Say I have a textfield - inputTextField
and a button on UI with action performActionDynamically
, in same class I define two functions: 1. firstFunc
, 2. secondFunc
, now I want to achieve this behavior:
If user types "firstFunc" in textfield and then he taps on button it should invoke firstFunc
function, and if he types "secondFunc" in textfield and then he taps on button it should invoke secondFunc
function.
In objective-c I would have easily achieved it by following below pseudocode:
performActionDynamically
pass inputTextField.text
in NSSelectorFromString()
to obtain selector performSelector:withObject:
on self to perform respective functionThe only thing which I can think in implementing same behavior in swift is -
firstFunc
, secondFunc
Is there any better way to achieve intended behavior? Please guide.
Upvotes: 1
Views: 114
Reputation: 566
You could try something like this:
if self.respondsToSelector(Selector(selectorString)) {
NSTimer.scheduledTimerWithTimeInterval(NSTimeInterval(0), target: self, selector: Selector(inputTextField.text), userInfo: nil, repeats: false)
}
This is done as a callback, so you will have to take that into account.
You could use NSThread instead of NSTimer if you prefer:
NSThread.detachNewThreadSelector(Selector(inputTextField.text), toTarget: self, withObject: nil)
Upvotes: 1