Create a storyboard named main and make sure to set it up an Main interface in the Deployment info of the project.
Create Start and Stop buttons along with two labels. One to display time and one to display messages. Make sure the buttons are IBActions. While in the header file, add the timer to the interface:
{
NSTimer *timer;
int countInt;
}
- Set countInt integer that we just assigned to zero and assign the label to it.
- Set the timer using
scheduledTimerWithTimeInterval:target:selector:userInfo:nil repeats: method. Set interval to 1.0 which represents the speed of the count, set self for target and @selector() with empty brackets for now. userInfo:nil, and YES for repeats boolean.
3. Create a helper counter method and leave it empty for now. So now we can go back to the @selector and fill out the rest of it so it looks like this: @selector(counter)
4. All our stopCounter button should be able to do is to stop the count. Can do it with a simple method: [timer invalidate];
5. Lets move on to the helper counter method.
Specify wether you want to count up or down. I put my countInt +=1; for now.
Setting the label
self.label.text = [NSString stringWithFormat:@”%i”, countInt];
Make the timer stop at zero: [timer invalidate];
Hit run and see that it works. The counter should start at zero, count up by one, at a speed one per second. Cool.
Now lets change it a bit. Set the countInt in the startCouner: method to 10 and move to the counter method. Make it count down: countInt -=1;
Then lets make it warn us when the time is almost up and print something out when the time is up. That’s when we get the second label involved. Use the following code:
if (countInt == 0) {
[timer invalidate];
self.label2.text = @”You lose!”;
} if (countInt == 5) {
self.label2.text = @”Time is almost up!”;
}
Hit run at see that it works. Profit!
Bitcoin tip jar: bc1qgpl6lhf09j6kcdvkh8cz90p4cfxuyfec3ecjrd
Ethereum tip jar: 0x7e0Bf6D50b5F5fcbf76A16Bd5285CE0c74C063a9
Originally published at objectivecmakesyouwanttopicklongnames.wordpress.com June 24, 2016.