Example for calling myMethod every 2 seconds - La Sierra University

11 downloads 129 Views 16KB Size Report
Example for calling myMethod every 2 seconds: [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(myMethod). userInfo:nil.
Example for calling the countDown method every second for 20 seconds and then stop: 1. Declare a global NSTimer variable in the interface of the .h file @interface viewController : UIViewController { NSTimer *myTimer; // Declare a global NSTimer variable }

2. Set up the timer to fire every 1 second, and call the countDown method when it fires. Put this code where you want to start the timer. myTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(countDown) userInfo:nil repeats:YES];

3. This countDown method is called automatically by the timer every 1 second as setup from step 2 above. The count variable must be declared as static so that it doesn’t get re-initialized every time that this method is called. Finally, the timer is disabled when count reaches 0. - (void) countDown { static int count=20; // Declare a static variable so that it doesn’t // get re-initialize each time NSLog(@"%i",count); // Display the countdown in the console if(count == 0) { // Stop the timer when count reaches 0 [myTimer invalidate]; myTimer = nil; } count--; }

// Decrement the count

Example for calling countDown and passing myObject to it every 2 seconds. myObject is the name of whatever object you want to pass. [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(countDown) userInfo:myObject repeats:YES]; -(void) countDown:(NSTimer*)timer { // Now you can access all of the properties and methods of myObject [[timer userInfo] myObject]; }