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.

1

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.