1.11. Implementing While Loops
Problem
You want to let a piece of code run over and over again until a certain condition is met.
Solution
Use while loops and specify your exit condition. Here is the format for the while loop:
while (<replaceable>condition</replaceable>){
CODE
}Note
As long as the condition is a value other than zero/nil/NULL, the while loop will run.
Discussion
The while loop is the arrogant brother of the for loop (see Recipe 1.10) because while loops only take a condition that should be met for the loop to run. If the condition is positive, the loop will always run until the condition becomes negative. For instance, a while loop could be implemented to make an icon in the Dock in Mac OS X jump up and down until the user taps on that icon (this is actually a very bad user experience; icons in the Dock shouldn’t jump up and down continuously, but for a short interval, or even a fixed number of times, usually 3). The exit condition for the while loop is the user’s tapping on that icon. As long as the user hasn’t tapped on the icon, the icon will jump up and down.
A while loop is awkward to use with a counter because of its syntax. If you require a counter to control your loop, it is better to use a for loop. If you do require a while loop but still want to have access to a counter, you will need to manage the counter manually, like so:
NSUInteger counter = 0;
while (counter < 10){
NSLog(@"Counter = %lu", (unsigned long)counter);
counter++;
}Just as you can have positive conditions ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access