swift 4 selector perform with multiple parameters - swift

I have function definition like this.
#objc func getSearchList(forString: String?, forPaging: Bool){
and I want to perform this function after waiting 0.5 second .(after text change but when fast change , remove callbacks and perform last added)
But when I perform like below, forString parameter is nil and not cancel old performs.Can someone help me? How can I send multiple parameter to selector and cancel previousperformRequests?
let selector = #selector(SearchViewController.getSearchList(forString : forPaging:))
NSObject.cancelPreviousPerformRequests(withTarget: self, selector: selector, object: previousSearchText)
self.perform(selector, with: forInputString, afterDelay: 0.5)
previousSearchText = forInputString

Related

Swift:"Unrecognized selector sent to instance", Xcode 9.4.1

Can anyone help me with this?
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate=self
tableView.dataSource=self
searchBar.autocorrectionType = .yes
searchBar.delegate=self
searchBarView.translatesAutoresizingMaskIntoConstraints=false
let tap:UIGestureRecognizer = UITapGestureRecognizer(target: self, action: Selector(("tapCancel:")))
searchBarView.addGestureRecognizer(tap)
tableView.addGestureRecognizer(tap)
tableView.isUserInteractionEnabled=true
}
...
func tapCancel(sender:UITapGestureRecognizer){
hideSearchBarView()
isSearchon=false
print("Tap cancel!")
}
Every time I tap the View, it crash.
"unrecognized selector sent to instance 0x7feb85d109e0"
I will appreciate any help!
Thanks!
I believe the reason is due to how method names get mapped between Swift and Objective-C, which underlies the Cocoa implementation and the whole target/action mechanism.
In your case, the Swift method:
#objc func tapCancel(sender:UITapGestureRecognizer)
...corresponds to the Objective-C selector:
-tapCancelWithSender:
Note: In order to work with the target/action paradigm (i.e., called by means of a selector), the method needs to be declared as #objc. The alternative attribute #IBOutlet (for use in conjunction with Interface Builder) also supports this. (tip of the hat to #rmaddy)
In order to remove the "withSender" part and get a selector that matches tapCancel:, you need to tell Swift to remove the argument label sender, like this:
func tapCancel(_ sender:UITapGestureRecognizer) // Notice the underscore (_)
Also, in line with the comment by #dan, perhaps you can use:
#selector(self.tapCancel(_:))
or more succinctly, as pointed by (thanks again) #rmaddy, just:
#selector(tapCancel)
(Xcode will try to autocomplete it to #selector(tapCancel(_:)), but the shorter syntax works as well and the method name is highlighted)
I was not familiar with the Selector() syntax you used, so I tried playing a bit with it, and behold:
(Selector does not match any method the compiler can "see").
(After adding "withSender", the compiler can match the method, but it suggests using the better #selector(... syntax).
As #rmaddy also pointed out in the comments, using the shorter #selector(doSomething) syntax (no colons, no underscore, no self) also does away with the problem of whether "withSender" is needed or not.
use
let tap:UIGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(tapCancel))
instead of
let tap:UIGestureRecognizer = UITapGestureRecognizer(target: self, action: Selector(("tapCancel:")))
And add #objc before method tapCancel()

Swift Selector with default argument

I have Write simple Code here
self.navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Cancel, target: self, action: Selector("cancelClick"))
Actual Function
func cancelClick(isAlert:String = "yes"){
self.dismissViewControllerAnimated(true, completion: { () -> Void in
if isAlert == "yes" {
Functions.displayAlert("called")
}
})
}
self.cancelClick() - Worked but if i didn't pass the argument
self.cancelClick(isAlert:"no") - Crashed
So what should be my selector if i have to pass argument in default perameter
tried with both Selector("cancelClick") and Selector("cancelClick:") but no luck.
The thing is that the parameter is not up to you. It is always the button (the "sender"), and that is the only thing it can be.
In other words, if you want this function to have a parameter, then by all means you will need to set your selector string as "cancelClick:" - the colon means that it takes a parameter. But that parameter must be the button:
func cancelClick(bbi:UIBarButtonItem?) {
However, you will notice that I have cleverly made this UIBarButtonItem parameter an Optional. Why do you think I did that? Because now you can also call it directly and pass nil:
self.cancelClick(nil)
Thus, cancelClick: now has a way to know whether the call comes from the tapping of a button or by a direct call - if bbi is not nil, the button was tapped; if bbi is nil, we were called directly from code. Sneaky, eh?
Another sneaky approach is to make the parameter an AnyObject:
func cancelClick(sender:AnyObject) {
The beauty of this is that you can call it with any kind of class instance. cancelClick can check the type of the sender. If it is a UIBarButtonItem (sender is UIBarButtonItem), then we were called by tapping the button. Otherwise, if called in code, you can pass in a string or anything else that this function might be prepared to deal with.
Don't use Selector("cancelClick:"), try instead just "cancelClick:" with the colon so you can pass an argument.
And as Matt said, the argument you must pass is the sender (the button) itself.

Dynamically performing an action based on string passed in textfield

Say I have a textfield - inputTextFieldand 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:
Within performActionDynamically pass inputTextField.text in NSSelectorFromString() to obtain selector
Invoke performSelector:withObject: on self to perform respective function
The only thing which I can think in implementing same behavior in swift is -
Define two closures with name firstFunc, secondFunc
Store the closures in a dictionary as values for keys - 'firstFunc' and 'secondFunc' respectively
Obtain respective closure from dictionary based on value in textfield
Invoke obtained closure
Is there any better way to achieve intended behavior? Please guide.
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)

extra argument userinfo in call

Get the compile error message from xCode with Swift language: "extra argument userinfo in call". the question is how to use userInfo data from timer to argument "userInfo" in notification center.
func onSetAudioWithTrackIndex(CurrentTrackIndex:Int, urlAudio: String){
........
//try to pass currentTrackIndex data to timerfire
playTimeClock = NSTimer.scheduledTimerWithTimeInterval(0.4, target: self, selector: "onSetPlayProgressTime:", userInfo: CurrentTrackIndex, repeats: true)
}
//Timerfire
func onSetPlayProgressTime(timer: NSTimer){
var currentTime = mediaPlayer.currentPlaybackTime
var playDuration = mediaPlayer.duration
var trackIndexDict = ["trackIndex" : timer.userInfo]
................
if currentTime == playDuration{
NSNotificationCenter.defaultCenter().postNotificationName(MPMoviePlayerPlaybackDidFinishNotification, object: self, userInfo: trackIndexDict)
}
return
}
Swift can give you slightly strange compiler errors sometimes, which amount to “there were multiple possible options, none of them worked, so here’s what’s wrong with one of them”. When the one it complains about is not the one you were trying for, this can be very strange
This is why Swift tells you so often that something is “not a Int8” even though that has nothing to do with what you were trying to do (huh, I was trying to concatenate two strings, what have Int8s got to do with anything? – it’s because one of the possible options for the + operator is to work on Int8s so that’s the one it chooses to complain about).
In this case, postNotificationName has multiple overloaded versions, one with 1 argument, one with 2, and one with 3 (the one you want). None of them fit the types you’ve supplied so it’s saying “one of the options is a call with 2 arguments, and you supplied 3, so that won’t work, there’s an extra argument”.
Unfortunately this is really quite confusing and throws you off the scent of what is actually wrong. Assuming you cut and pasted your actual code, looks like there’s a spelling error in MPMoviePlayerPlaybackDidFinishNotification, and the userInfo argument label is missing a colon after it.
(p.s. you don’t need to explicitly put a return at the end of functions that return void, though it doesn’t do any harm)
In swift 3 , I got this same error. When I was converting the swift 2.2 to swift 3, as the syntax was changed so it throws this error.
Swift 3:
NotificationCenter.default.post(name: NSNotification.Name(rawValue: MPMoviePlayerPlaybackDidFinishNotification), object: self, userInfo: trackIndexDict)
The problem is
that the userInfo property of NSTimer is an optional:
var userInfo: AnyObject? { get }
so that trackIndexDict has the type [String : AnyObject?] which is not convertible
to [NSObject : AnyObject] as expected by the last parameter of postNotificationName().
With optional binding you can "test and unwrap" the property:
if currentTime == playDuration {
if let timerInfo: AnyObject = timer.userInfo {
let trackIndexDict = ["trackIndex" : timerInfo]
NSNotificationCenter.defaultCenter().postNotificationName(MPMoviePlayerPlaybackDidFinishNotification,
object: self,
userInfo: trackIndexDict)
}
}
thanks, Martin, this(userInfo of NSTimer is optional) is root cause. with the below change. this can be fixed
if let timerUserInfo: AnyObject = timer.userInfo! {
NotificationCenter.default.post(name: NSNotification.Name(rawValue: MPMoviePlayerPlaybackDidFinishNotification), object: self, userInfo: ["trackIndex":timerUserInfo])
}

Default Parameters

I have a function with one parameter. This parameter has a default value. (true)
func disableButton(animated: Bool = true) {
if (animated) {
...
} else {
...
}
}
So i can call the function as:
disableButton(animated: true)
or:
disableButton()
and they give me the same result.
Now I have an NSTimer running a selector on completion like this:
buttonFadeTimer = NSTimer.scheduledTimerWithTimeInterval(NSTimeInterval(1.5), target: self, selector: Selector("disableButton"), userInfo: nil, repeats: false)
It will send the disableButton() message on completion. However on completion it causes the app to crash.
If i do:
func disableButton() {
disableButton(animated: true)
}
Then the timer successfully sends that message and the app does not crash.
Of course this is really ugly and kind of limits the great Swift feature of default parameters.
Is this a bug (that I should report) or am I doing it wrong?
Thanks for any help!
There's a difference between -disableButton and -disableButton: selectors. But you can't just use your desired selector like this:
buttonFadeTimer = NSTimer.scheduledTimerWithTimeInterval(NSTimeInterval(1.5), target: self, selector: Selector("disableButton:"), userInfo: nil, repeats: false)
because NSTimer here assumes selector with no arguments or selector with single argument (which will be used to pass firing NSTimer instance).
I believe, you should migrate from using selectors, as you want to use all that great features Swift delivers, as far as selectors is outdated pattern.
Just a note: it could work if you use "disableButton:" selector, maybe NSTimer's pointer will be interpreted as true and maybe not, not sure what will happen (maybe it could crash due to Swift strong typing stuff). But depending on that behaviour is a bad practice which could lead to bugs which are extremely hard to exterminate.