Is it possible to restart the for loop on its first iteration?

In Objective-C, is it possible to restart the first iteration of the for loop? I do not want to do anything with my objects until I find a “good” object, after which I want to go back and do everything with each object to this good object.

So,

bool someflag = false; for (id object in array) { if(object is good) { someflag = true; //restart to first object in loop } if(someflag) { doStuffWithObject(object); } } 

Or is there another / better way to do what I'm trying to do?

Obviously, a simple way would be to simply have two separate for loops, so if I could get a second opinion telling me that the best way is what I will shoot for. For some reason, I have a feeling that there must be a better way.

+6
source share
4 answers

Not with a quick enumeration, no (with the exception of goto ), however, if you are using an indexed access approach, you can:

 NSUInteger count = [array count]; for (NSUInteger i = 0; i < count; i++) { bool someflag = false; id object = array[i]; if (isgood(object)) { someflag = true; //restart to first object in loop i = 0; } if(someflag) { doStuffWithObject(object); } } 
+5
source

If you really want to do this (instead of using a second loop, which is almost certainly simpler), you can use the good old goto :

 bool someflag = false; restart: for (id object in array) { if(!someflag && object is good) { someflag = true; goto restart; } if(someflag) { doStuffWithObject(object); } } 
+3
source

Consider using indexOfObjectPassingTest: to separate the logic of your code between checking (and getting an index) on a "good" object and then processing it.

+1
source

you can use while loop for this

 acutualElement = array.objectAtIndex[0]; int i = 0; while(actualElemtnt =! null) { if(...){ do smth; } else { do smth different; } if (exit condition reached) { atualelement = null; } else { if (i < array.size) i++; //next element in array else i = 0; //first element in array actualElement = array.objectAtIndex[i]; } } 
0
source

Source: https://habr.com/ru/post/972249/


All Articles