Reputation: 516
I was doing some programming in Cocoa Touch and Objective-C, and now I have a really frustrating problem. I have a method in which there is a for-loop. Yet, every time I run the app in the iOS Simulator, the code in the loop isn't run, and it doesn't stop on any breakpoints within the loop. At first, I thought it was just in the method, but it appears now that it happens anywhere in the code. No for-loops work anywhere in any methods. Here is an example of one of my loops, and if you see anything wrong, I would appreciate the help.
for (int i = 0; i == 3; i++) {
NSLog(@"This is a test.");
}
This might be something really dumb that I am missing, but I can't see anything that could be causing this. If you need more code, just ask, and thanks in advance!
Upvotes: 0
Views: 491
Reputation: 796
The condition on a for loop causes the loop to run as long as the condition is true.
In the example you cited, the loop will never execute because i started off equal to zero, with the test condition i == 3. Since i == 3 is immediately false, the loop does not run even once.
If your intention was to run the loop until i was three, then the test condition should be i < 3 making the entire for
for (int i = 0; i < 3; i++) {
Another way to think about this is that the loop will continue to run "while i < 3".
I hope this helps.
Upvotes: 5
Reputation: 44701
I think your loop should look more like this:
for (int i = 0; i <= 3; i++) {
NSLog(@"This is a test.");
}
Upvotes: 0
Reputation: 16861
A for loop runs as long as the continuation condition is true. Change "i==3" to "i <= 3".
Upvotes: 1
Reputation: 17906
The second part of a for-loop—in your code, i == 3
—is a test that is checked before each iteration of the loop. If the test is false, the loop is ended. Since i is 0 on the first iteration, i == 3
is false.
You probably want either i <= 3
or i < 3
as your conditional.
Upvotes: 1
Reputation: 1560
may be try
for(int i = 0; i < 4;i++){
NSLog("This is a test");
}
Upvotes: 0