2011-12-27 35 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]; 
    } 
}