Iphone 延迟后执行一个方法

Iphone 延迟后执行一个方法,iphone,ios,objective-c,ipad,Iphone,Ios,Objective C,Ipad,我想在-touchesend方法完成执行后2秒执行一个方法-recognized。但是,如果用户在这2秒内触碰了什么东西,则不得执行该方法。下次再次执行-touchesend方法后,必须再次设置计时器以等待2秒。等等希望这个问题足够清楚。如果没有,一定要告诉我。您需要使用一个来协调这一点。触发要启动计时器的事件时,请使用scheduledTimerWithTimeInterval:target:selector:userInfo:repeats:在两秒钟内计划函数调用 使用视图控制器全局的布尔变

我想在-touchesend方法完成执行后2秒执行一个方法-recognized。但是,如果用户在这2秒内触碰了什么东西,则不得执行该方法。下次再次执行-touchesend方法后,必须再次设置计时器以等待2秒。等等希望这个问题足够清楚。如果没有,一定要告诉我。

您需要使用一个来协调这一点。触发要启动计时器的事件时,请使用scheduledTimerWithTimeInterval:target:selector:userInfo:repeats:在两秒钟内计划函数调用

使用视图控制器全局的布尔变量,以防止计时器设置在两者之间

这里有一个粗略的想法:

BOOL shouldRespondToTouch = YES;

- (void)touchesEnded {
    [NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(doAction) userInfo:nil repeats:NO];
    shouldRespondToTouch = NO;
}

- (void)doAction {
    shouldRespondToTouch = YES;
    // Do stuff here
}

事实证明,这真的很简单

在视图中创建ivar。h

NSDate *startDate;
将以下内容添加到view.m中的这些方法中

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
self->startDate = [NSDate date];
NSLog(@"%@", startDate);
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
if (self->startDate) {
        NSTimeInterval ti = [[NSDate date] timeIntervalSinceDate:self->startDate];
        NSLog(@"Time: %f", ti);
        if (ti >= 2 ) {
            NSLog(@"Yes, greater than 2 seconds !");
        }
    }
}

非常有魅力。

谢谢@woz,+1。然而,我找到了一个可能更好的方法。
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
self->startDate = [NSDate date];
NSLog(@"%@", startDate);
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
if (self->startDate) {
        NSTimeInterval ti = [[NSDate date] timeIntervalSinceDate:self->startDate];
        NSLog(@"Time: %f", ti);
        if (ti >= 2 ) {
            NSLog(@"Yes, greater than 2 seconds !");
        }
    }
}