0

I'm using AppKit.NSSearchField and need to delay search event while user is typing, for example to filter data after 2 sec.

I have added action from interface builder - 'On end editing', but it is called too often while typing . Is there any native way to increase delay time while user is typing?

enter image description here

Nininea
  • 2,671
  • 6
  • 31
  • 57
  • You could use timer which will fire off on end editing. And then upon it runs out you run selector search. Something like this: let delay =2 // time in seconds NSTimer.scheduledTimerWithTimeInterval(delay, target: self, selector: #selector(search), userInfo: nil, repeats: false) – Irfan Dec 01 '16 at 20:20
  • Thanks for answer @Irfan So, I should add custom delay, it is not possible to increase delay time for this control? – Nininea Dec 01 '16 at 20:25
  • 1
    I am quite confident that is the case - as the name suggests "on end editing". Otherwise it would be called something like "on end editing with delay" :) – Irfan Dec 01 '16 at 20:34
  • What is the c# tag for? How are you getting the text change notification? Don't use NSTimer. Use dispatch_after. – El Tomato Dec 01 '16 at 21:53

1 Answers1

2

You should use a technique named debouncing. The idea is to execute a method from inside of your action (which you connected to "on end editing") after kinda expiring delay. Every new key press will reset timer, which has fixed delay. Until user keeps typing, the search will not execute. As soon as he stops, last debounce timer will fire off and your search will go thru.

More information here: How can I debounce a method call?

Community
  • 1
  • 1
Eugene Mankovski
  • 1,180
  • 10
  • 16
  • this.timer?.Invalidate (); this.timerDetails = NSTimer.CreateScheduledTimer (NSConstants.SearchDelaSec, (obj) => { FilterData (); }); here is my solution, but it has problems. doesn't work as expected – Nininea Dec 04 '16 at 13:31
  • 1
    @Nininea Your code when fixed a bit, works just fine. I created an example with 1second delay: https://github.com/emankovski/DebouncedSearch – Eugene Mankovski Dec 04 '16 at 22:04