Tuan Anh Vu Tuan Anh Vu - 3 years ago 207
Swift Question

Detect when user stopped / paused typing in Swift

I've dug around stackoverflow and found the solution which I converted to Swift, it doesn't seem to work and the selector is still being performed.

func searchBar(searchBar: UISearchBar, textDidChange searchText: String) {
self.filter.searchTerm = self.searchBar.text

NSObject.cancelPreviousPerformRequestsWithTarget(self, selector: "getHints", object: nil)
NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: "getHints", userInfo: nil, repeats: false)
}


Is there a better way to do this in swift?
Thanks!

Answer Source

In swift NSObject does not have the convenience methods performSelector and friends (including cancelPreviousPerformRequestsWithTarget). Probably Apple thought they are not needed or want us to use other newer technologies like GCD timers ... who knows for sure.

The truth is that NSObject uses NSTimers plus a couple of things to accomplish performSelector. This is an example for a UITextField but you can adjust it for your UISearchBar easily :)

var timer: NSTimer? = nil

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
    println("shouldChangeCharactersInRange")
    timer?.invalidate()
    timer = NSTimer.scheduledTimerWithTimeInterval(0.5, target: self, selector: Selector("getHints:"), userInfo: textField, repeats: false)
    return true
}

func getHints(timer: NSTimer) {
    println("Hints for textField: \(timer.userInfo!)")
}

Note that I am passing the textField as the userInfo so you can use it inside getHints:. Not always needed but providing it will make your life easier specially in cases when your target is not self or you are handling various text fields.

How this is different from NSObject performSelector and friends?

When you call (in objc) NSObject performSelector the target is retained but when you use NSTimer directly (like in this case) its target is NOT retained. . This means that you have to make sure target is alive when the timer fires. Otherwise the app will crash.

If you are interested in GCD timers this gist a good place start: maicki/TimerWithGCD.md

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download