Reputation: 268
I'm trying to implement a method that gets called in the touchesBegan
method when I tap the screen. How do I add a delay so the method increment
has a downtime of 2 seconds before it can be called again?
int i;
-(void)increment
{
i++;
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
/* Called when a touch begins */
for (UITouch *touch in touches) {
CGPoint location = [touch locationInNode:self];
[self increment];
}
}
Upvotes: 0
Views: 160
Reputation: 926
Alternative method for sprite-kit.
int i;
-(void)increment
{
[self runAction:[SKAction sequence:@[[SKAction waitForDuration:2.0], [SKAction runBlock:^{
i++;
}]]]];
}
Upvotes: 0
Reputation: 11555
If I understand your question correctly and you are trying to prevent from calling the code inside of touchesBegan more frequently than every 2 seconds, you can add a NSDate variable and set it with current date when the code is executed. Then add something like
if NSDate().timeIntervalSinceDate(timeStamp) > 2 {
// execute your code
for touch in touches {
var location = touch...
increment()
}
}
timeStamp = NSDate() // wait period starts again
}
The example is in Swift, not Objective C, I hope it is ok.
Upvotes: 0
Reputation: 5911
One way to do this is to enhance your increment
method to perform its regular functionality only if the 2 seconds have elapsed, which is verified using a bool variable.
Example:
BOOL incrementMethodLocked = NO;
-(void)increment
{
if(incrementMethodLocked)
return;
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 2 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
incrementMethodLocked = NO; // unlocks method for future use
});
i++;
incrementMethodLocked = YES; // locks method
}
Upvotes: 3
Reputation: 1344
So I think you could use temporary data storage like CoreData. But it's not necessary at your situation. PList or NSUserDefault better way to store cached value or kind of data. Store last 2 second after that in your method create an "if condition" and you can specify NSTimer method with delay.
Upvotes: -2