2011-05-17 57 views
1

,這是另一個新手問題 - 流程/工作流程問題。請耐心等待。基於「自來水」我怎麼訪問定時器對象並停止處理

我有一個的NSTimer對象,計時器,在一個方法梅塔創造,傳遞到它是用來contorl一些處理的另一種方法methB。兩種方法都屬於同一類。

我有touchesBegin和touchesEnded方法來捕捉用戶輸入。這些方法與我之前的兩個方法 - methA和methB在同一個類中。當用戶「點擊」我的屏幕上我需要停止處理

當我的touchesBegin方法是由水龍頭調用我假設我所要做的就是發送一條消息給我的其他方法,methA/methB和告訴他們停止處理。我假設我所要做的就是使傳遞給我的「處理」方法(即methB)的計時器無效。

這聽起來是正確的?我已經包含了我的四個方法touchesBegin,methA和methB。任何輸入是不勝感激。

- (void) methA 
{ 

    stepValue = 0; 
    animationBuild = YES; 

    float duration = [[[Config shared] valueForKey:@"animation.val.step_duration"] floatValue]; 

    [NSTimer scheduledTimerWithTimeInterval:duration target:self selector:@selector(stepValue:) userInfo:nil repeats:YES]; 

} 

- (void) methB:(NSTimer *) timer 
{ 
    if (animationBuild) 
    { 
     // animation logic/processing 
    } 

    // Next step 
    stepValue++; 

    if (stepValue == GROUP_SIZE) 
    { 
     [timer invalidate]; 

     [self animateShowMessage]; 

    } 
} 


- (void) touchesBegan:(NSSet *) touches withEvent:(UIEvent *) event 
{ 
    if (modalDialog) 
    { 
     return;   
    } 

    if (currentTouch == nil) 
    { 
     UITouch *touch = [[touches allObjects] objectAtIndex:0]; 

     currentTouch = [touch retain]; 
    } 
} 


- (void) touchesEnded:(NSSet *) touches withEvent:(UIEvent *) event 
{ 
    if (modalDialog) 
    { 
     return;   
    } 

    UITouch *touch = [[touches allObjects] objectAtIndex:0]; 

    if ((touch != nil) && (touch == currentTouch)) 
    { 
     CGPoint touchPoint = [touch locationInView:self.view]; 

     else if ((CGRectContainsPoint(visRect[[Process shared].procType], point)) && (touch.tapCount == 2)) 
      {    
       // processing 
      } 

     else 
     { 
      // Start a new processing 
      [self startNew]; 
     } 

     [currentTouch release]; 
     currentTouch = nil;   
    } 
} 

回答

2

這基本上是正確的,但是,我會進行一些設計更改。

除非您正在爲iOS 3.x之前的應用程序構建,否則您應該使用UIGestureRecognizer來識別輕敲,而不是使用較老的touchesBegan方法。使用識別器是很容易的:

UITapGestureRecognizer *tapRecognizer = 
    [[[UITapGestureRecognizer alloc] initWithTarget:self 
            action:@selector(handleTap:)] autorelease]; 
[self.view addGestureRecognizer:tapRecognizer]; 


我通常不喜歡在我的代碼不止一個地方,我修改的計時器。如果您在整個代碼中分散了計時器修改,那麼您很可能會錯過某個地方的失效或釋放。所以,我通常創建一個計時器屬性,如下面的例子。如果您使用這樣的屬性,更改您的計時器對象或將您的計時器設置爲零將自動使其無效,因此它保證永遠不會處於時髦狀態。

- (void)setTimer:(NSTimer *)newTimer { 
    [_timer invalidate]; 
    [newTimer retain]; 
    [_timer release]; 
    _timer = newTimer; 
}