views:

85

answers:

1

Although I'm coding in Objective C, this is more of a general programming question.
What is the best way to convert a constantly changing scalar value to a changing interval or frequency?

Right now every time the scalar value changes I am destroying the NSInterval
ie

   [self.myTimer invalidate];
    self.myTimer = nil;

and creating a new one, but this seems like a VERY expensive way to achieve my goal, since the changing scalar value in my case represents the horizontal velocity of a swipe.

For a rough analogy, think of the speed of a swipe being reflected in a visual metronome, the faster you swipe, the higher(shorter interval) the frequency of the metronome.

+1  A: 

First, understand that this is a "measurement" problem. To solve this problem, isolate the minimum attributes needed to solve the problem and derive the rest.

The distance moved and the time taken to move the distance are derived attributes of each measurement, in this case the measurement is named "swipe". In a racing analogy, the measurement is called a lap. The "speed" can now be calculated. This will be the "velocity", which is simply distance/time.

The distance can be calculated given the start and end points of the swipe. To obtain the time value, create an startTime instance of NSDate in touchesBegan:withEvents: and in touchesEnded:withEvents: calculate elapsedTimeInterval using [startTime timeIntervalSinceNow];

Depending on your needs, you may need a Measurement class with properties for startPosition, endPosition, startTime and endTime so you can keep track of "fastest" speed etc.

Take a look at Analysis Patterns by Martin Fowler. I find it very useful when trying to map domain problems to software solutions.

falconcreek
Thanks. Ended up reworking my problem, keeping a constant interval(derived from touches moved) calculating my velocity based on distance moved per time interval, and then mapping this change in velocity to the scalar value I needed.
eco_bach