Resolved Timer update help

Discussion in 'iPhone/iPad Programming' started by nickculbertson, Jun 1, 2011.

  1. nickculbertson, Jun 1, 2011
    Last edited: Jun 1, 2011

    macrumors regular

    nickculbertson

    Joined:
    Nov 19, 2010
    Location:
    Nashville, TN
    #1
    Hello,
    I have a sound that plays when a button is touched. 17 seconds later I want another action to be called using performSelector to stop the sound. If the first button is touched again before the 17 seconds have been reached I want the counter to restart. How can this be done?
    Code:
    -(IBAction) push{
    [sound play];
    [self performSelector:@selector (stop) withObject:nil afterDelay:17.];
    }
    
    -(void) stop{
    [sound stop];
    }
    
    Thanks,
    Nick
     
  2. macrumors 603

    Joined:
    Aug 9, 2009
    #2
    As always, start by reading the class reference doc:
    http://developer.apple.com/library/.../Classes/NSTimer_Class/Reference/NSTimer.html

    From the class reference doc, you should be able to figure out how to do the following. What follows is a simple breakdown of your description into logical steps. You should be able to do simple breakdowns like this yourself; it's an important skill called decomposition.
    http://en.wikipedia.org/wiki/Decomposition_(computer_science)


    Make and schedule an NSTimer using
    +scheduledTimerWithTimeInterval:target:selector:userInfo:repeats

    Take ownership of the timer, and store in an ivar (or assign to a retain'ed property) for later use.

    When the button is pressed, look at the stored timer. If it's valid (what method for this?), then the 17 sec interval has not expired. Do action A. If the stored timer is nil or invalid, then the interval has expired. Do action B. The actions A and B are whatever are relevant to playing or stopping the sound, etc.

    When the timer fires, the interval has expired, so do action B. That is, action B should be used as the target/action when the timer was first made.

    When the timer's use is completed (after action A or B), remove it from storage. Consider whether this can be done as part of actions A and B.
     
  3. thread starter macrumors regular

    nickculbertson

    Joined:
    Nov 19, 2010
    Location:
    Nashville, TN
    #3
    Thanks for the tip, chown33.

    This did the trick

    Code:
    -(IBAction) push{
    [sound play];
    [time1 invalidate];
    time1 = [NSTimer scheduledTimerWithTimeInterval:17.0 target:self selector:@selector(stop) userInfo:nil repeats:NO];
    }
    
    -(void) stop{
    [sound stop];
    time1=nil;
    }
    Thanks,
    Nick
     

Share This Page