Our first example demonstrates the use of timers in Objective-C. We’ll look at how to schedule code execution for the future or at regular intervals.
In this Objective-C code:
We use dispatch_after to create a timer that fires once after 2 seconds. This is similar to the time.NewTimer in the original example.
We use a Grand Central Dispatch (GCD) timer (dispatch_source_t) to create a repeating timer. This is more flexible than the single-fire timer and can be cancelled, similar to the second timer in the original example.
We cancel the second timer immediately after creating it, demonstrating how to stop a timer before it fires.
We use [NSThread sleepForTimeInterval:] at the end to wait for 2 seconds, giving the second timer time to fire if it was going to.
To run the program, save it as Timers.m and compile it using:
Then run it:
The output shows that Timer 1 fires after about 2 seconds, while Timer 2 is stopped before it has a chance to fire.