2

I"ve got a problem in a for loop I'm putting a NSArray into a tableview and I want the last object to be in the first cell, but it only works with the first object.

this works:

for(int i = 0; i < messages.count ; i++)
    {
    }

but this doesn't:

 for(int i = messages.count; i > 0; i--)
    {
    }

and the error message is:

Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[__NSArrayM objectAtIndex:]: index 203 beyond bounds [0 .. 202]'
*** First throw call stack:
(0x32bd33e7 0x3a8c4963 0x32b1eef9 0x891d3 0x34a01579 0x34a561f7 0x34a5613d 0x34a56021 0x34a55f4d 0x34a55699 0x34a55581 0x34a26561 0x349e58c7 0x34791513 0x347910b5 0x34791fd9 0x347919c3 0x347917d5 0x349eb93f 0x32ba8941 0x32ba6c39 0x32ba6f93 0x32b1a23d 0x32b1a0c9 0x366f833b 0x34a362b9 0x8549d 0x3acf1b20)
libc++abi.dylib: terminate called throwing an exception
Rob
  • 15,732
  • 22
  • 69
  • 107
hannsch
  • 285
  • 1
  • 3
  • 5

3 Answers3

4

you need to start the loop at the message count -1 so like this:

for (int i = messages.count - 1; i >= 0; i--) 
{
   ...
}

Since messages.count will give the total number of elements held within the messages object. The greatest element index in the array will be the messages.count - 1 since the array indices start at 0.

Will Andrew
  • 693
  • 1
  • 10
  • 29
1

for(int i = 0; i < messages.count ; i++) loops from 0 up to messages.count-1 (it stops when i == messages.count).

for(int i = messages.count; i > 0; i--) loops from messages.count down to 1, an entirely different set of indices.

Write

for(int i=messages.count-1; i>=0; i--)

instead, or use this:

int i = messages.count;
while(i --> 0) {
    ...
}

or just use reverseObjectEnumerator:

for(id element in [messages reverseObjectEnumerator]) {
    ...
}
Community
  • 1
  • 1
nneonneo
  • 171,345
  • 36
  • 312
  • 383
0

Half-open intervals. There's no object at [array objectAtIndex:array.count]. If, for example, your array contains 5 objects, then there are objects at indices 0, 1, 2, 3 and 4.

Also, in the second case, the counter needs to go until 0, else you don't take the first object (the one at index 0) into consideration (again: the closed part of the half-open interval is at 0, the open one is at array.count).

All in all: change the second loop to

for (int i = messages.count - 1; i >= 0; i--)

and it will work fine.