2011-12-27 71 views
6

我正在我的第一个iOS应用程序,并已运行在第一个障碍,我一直没能找到一个很好的答案。Objective C&iOS:运行一个计时器? NSTimer /线程/ NSDate /等

问题:我有一个自定义的UIGestureRecognizer,并且它已全部正确连线,并且我可以在识别后为@selector中的每个触摸运行代码。这在大多数情况下都很好,但对于其他人来说这有点太多了。

我的目标:制作一个计时器,以指定的时间间隔触发以运行逻辑,并且可以在取消触摸时取消此操作。

为什么我在这里问:解决方案有很多可能性,但没有一个能够最好地实现。到目前为止,好像

  • performSelector(有些变化对这个)
  • NSThread
  • NSTimer
  • NSDate
  • 操作队列
  • 我想我发现了一些其他人也...

从所有研究来看,某种形式的制作线程似乎是要走的路线,但我对这种情况最适合的方式感到不知所措。

实施示例:每0.10秒取一个NSPoint,并取前一个点与当前点之间的距离。 [考虑到每个点之间的距离会产生非常混乱的结果]。

相关的代码:

- (void)viewDidLoad { 
CUIVerticalSwipeHold *vSwipe = 
[[CUIVerticalSwipeHold alloc] 
initWithTarget:self 
action:@selector(touchHoldMove:)]; 
[self.view addGestureRecognizer:vSwipe]; 
[vSwipe requireGestureRecognizerToFail:doubleTap]; 
} 

... 

- (IBAction)touchHoldMove:(UIGestureRecognizer *)sender { 
    if (sender.state == UIGestureRecognizerStateEnded) { 

    } 

    if (sender.state == UIGestureRecognizerStateBegan) { 

    } 

    //other stuff to do goes here 

} 

回答

11

使用一个NSTimer

设置它是这样的:

theTimer = [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(yourMethodThatYouWantRunEachTimeTheTimerFires) userInfo:nil repeats:YES]; 

然后,当你想取消它,做这样的事情:

if ([theTimer isValid]) 
{ 
    [theTimer invalidate]; 
} 

请注意,在上面的例子中,您需要声明NSTimer的“theTimer”实例,它可用于这两种方法。在上面的例子中,“0.5”表示定时器每秒会触发两次。根据需要调整。

+1

注:在无效之后将定时器设置为零是一种很好的做法:[theTimer invalidate]; theTimer =零; – Groot 2013-04-09 10:19:41

1

为了完整起见,我在这里将我的最终实现(不知道这是要做到这一点,但在这里不用)

.H

@interface { 
    NSTimer *myTimer; 
} 

@property (nonatomic, retain) NSTimer *myTimer; 

.M

@synthesize myTimer; 

------------------------------------------- 

- (void)viewDidLoad { 
//Relevant snipet 
CUIVerticalSwipeHold *vSwipe = 
[[CUIVerticalSwipeHold alloc] 
initWithTarget:self 
action:@selector(touchHoldMove:)]; 
[self.view addGestureRecognizer:vSwipe]; 
[vSwipe requireGestureRecognizerToFail:doubleTap]; 
} 

------------------------------------------- 

- (IBAction)touchHoldMove:(UIGestureRecognizer *)sender { 
    if (sender.state == UIGestureRecognizerStateEnded) { 
     //Cancel the timer when the gesture ends 
     if ([myTimer isValid]) 
      { 
       [myTimer invalidate]; 
      } 
     } 
    } 

    if (sender.state == UIGestureRecognizerStateBegan) { 
     //starting the timer when the gesture begins 
     myTimer = [NSTimer scheduledTimerWithTimeInterval:someTimeIncrement 
                target:self 
               selector:@selector(someSelector) 
               userInfo:nil 
                repeats:YES]; 
    } 
}