I have a NSMutable array with elements inserted like this:
[availableSeatsArray addObject:[NSString stringWithString:num_available]];
I want to remove the elements in the array that have values of zero or lower. I tried checking the element’s value using its int value and even its string value, but it always passes the ‘0’ element case. Console output of the array before and after below.
for (int i=0;i<[availableSeatsArray count]; i++) {
if ([[availableSeatsArray objectAtIndex:i] intValue] <= 0 || ([[availableSeatsArray objectAtIndex:i] isEqualToString:@"0"])) {
NSLog(@"Removed index: %d", [[availableSeatsArray objectAtIndex:i] intValue]);
[availableSeatsArray removeObjectAtIndex:i];
}
}
Console output:
Available array: (
"-2",
10,
5,
"-5",
0,
10,
10,
)
2012-08-14 11:13:28:002 -[dmbAddReservation viewWillAppear:] [Line 1074] Removed index: -2
2012-08-14 11:13:28:004 -[dmbAddReservation viewWillAppear:] [Line 1074] Removed index: -5
2012-08-14 11:13:28:006 -[dmbAddReservation viewWillAppear:] [Line 1083] Available array: (
10,
5,
0, // I cannot explain why this element was not removed
10,
10,
)
The problem is that this approach uses a fundamentally flawed logic. It erronously doesn’t remove consecutive occurrences of 0 or negative objects. The reason is, when in the for loop you check for “-5”, it passes the test, then you remove it, shrinking the array, and shifting its remaining elements so that the “0” will now be in the place of the “-5”. But in the for loop, you advance the loop variable (i in this case) regardless of whether an element was or wasn’t removed, so now ‘i’ points one past the zero. And it wouldn’t be checked. Solution: only increase the loop variable if there are no consecutive elements that pass your test (i. e. change the if to while):