0

I have 5 objects in Array and want to delete 2 in loop but I have a small minor problem in below code

NSMutableArray *totalPages = [[NSMutableArray alloc] init];
[totalPages addObject:@"Test1"];
[totalPages addObject:@"Test2"];
[totalPages addObject:@"Test3"];
[totalPages addObject:@"Test4"];
[totalPages addObject:@"Test5"];

int currentPage = 2;

for (int x = 0; x < [totalPages count]; x++) {

    //int pageIds = [[totalPages objectAtIndex:x] intValue];
    //NSLog(@"%d",pageIds);

    NSLog(@"Array Count %d", (int)[totalPages count]);
    NSLog(@"Current Page %d", currentPage);
    NSLog(@"Current Iterator Value %d", x);

    if (x > currentPage) {

        [totalPages removeObjectAtIndex:x];

        NSLog(@"Array Count %d", (int)[totalPages count]);
        NSLog(@"Number of Pages to be removed %d", x);
    }
}

As I want to delete "Test4" and "Test5" but my above code is deleting only "Test5" and if I keep this logic as

if (x >= currentPage)   

so it deletes my "Test4" and "Test5" objects but logic fails when int currentPage = 0; so what is the recommended approach to delete Test4 and Test5 as objects in arrays are dynamically added and when currentPage = 0; so Arrays has only 1 Object in it as a pages.

user366584
  • 1,016
  • 1
  • 16
  • 34
  • possible duplicate of [Best way to remove from NSMutableArray while iterating?](http://stackoverflow.com/questions/111866/best-way-to-remove-from-nsmutablearray-while-iterating) – Hot Licks Sep 21 '14 at 18:05

1 Answers1

2

The array is changing as you deleting elements from it, it is getting shortened.

Adjust your for statement and count backwards, that should solve the problem for you.

Peter Pei Guo
  • 7,770
  • 18
  • 35
  • 54