Jason Murphy
Jason Murphy

Reputation: 35

What could cause a for loop to not increment and then increment by two?

I am not sure how this is possible but I have a for loop not incrementing properly through an array.

Basically what I have is:

for (AISMessage *report in disarray){
    NSLog(@"Position of array = %ld\n", [aisArray indexOfObject:report]);
}

There is more code in the loop but is nothing strange just formatting some of the data in the object and outputting it to a file.

The output of these lines would look something like:

Position of array = 0

...

Posiiton of array = 78176

Posiiton of array = 78177

Posiiton of array = 78178

Posiiton of array = 78178

Posiiton of array = 78180

Posiiton of array = 78181

...

Posiiton of array = 490187

For some reason the report at index 78178 gets read in twice and the report at 78179 gets skipped completely.

Any ideas on what may cause this?

I am totally confused.

Thanks in advance, Jason

Upvotes: 1

Views: 73

Answers (2)

Lasse V. Karlsen
Lasse V. Karlsen

Reputation: 391326

The object occurs twice in the array, so the indexOfObject finds the element at index 78179 at index 78178.

In other words, you have this case:

...
[78177] = x
[78178] = y
[78179] = y
[78180] = z
...

Also, you're not searching the same array you're iterating over, that might have something to do with it as well.

Since the positions reported are so high, I would try to find a better data structure than a simple array. For it to report a position of 78178, it will have to have compared the object against the preceeding 78177 elements, and this will only take more and more time as you get further into the array.

Upvotes: 3

Peter M
Peter M

Reputation: 7493

From the posted code you are iterating over AISMessage objects in the disarray array, but you are reporting on the position of the object in the aisArray array.

I have no idea if these are meant to be the same array or not. But if they are different arrays, then do you expect the objects to be in the same order?

Upvotes: 1

Related Questions