I have an NSMutableArray in Objective-C that I want to remove items from so that it has just the number of items that will be displayed in a grid on the screen. The number of items varies, but on one screen it is 9. The array has more items, but I don’t necessarily know how many. [Remember that array items are numbered with an index starting at 0. So the last index number of my array of 9 items is 8′]
This is the original code that I tried.
NSUInteger itemsOnScreen = 9;
for (NSUInteger i = itemsOnScreen; i < gridItems.count; i++) {
[gridItems removeObjectAtIndex:i];
}
This code doesn’t delete all of the items so I decided to start at the end and delete items until I there were only 9 left. This is the code that I ended up using.
NSUInteger itemsOnScreen = 9;
for (NSUInteger i = gridItems.count - 1; i > itemsOnScreen - 1; i--) {
[gridItems removeObjectAtIndex:i];
}
It’s kind of ugly and after working with it it occurred to me why the original code didn’t work. As I started deleting items, the number of items, and hence the index of the last item changed. So it worked fine for the first few, but as I neared the end of the loop, there were no items with an index that matched i. If I just delete the first item after the 9 that I want, then the loop works fine.
NSUInteger itemsOnScreen = 9;
for (NSUInteger i = 0; i < gridItems.count; i++) {
[gridItems removeObjectAtIndex:itemsOnScreen];
}