简体   繁体   English

NSArray不删除对象

[英]NSArray not removing objects

I have 5 objects in Array and want to delete 2 in loop but I have a small minor problem in below code 我在Array中有5个对象,想要在循环中删除2个对象,但是下面的代码有一个小问题

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 因为我想删除“ Test4”和“ Test5”,但是我上面的代码仅删除“ Test5”,如果我保持此逻辑为

if (x >= currentPage)   

so it deletes my "Test4" and "Test5" objects but logic fails when int currentPage = 0; 因此它删除了我的“ Test4”和“ Test5”对象,但是当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; 因此,当动态添加数组中的对象并且currentPage = 0时,建议删除Test4和Test5的方法是什么? so Arrays has only 1 Object in it as a pages. 因此,数组中只有1个对象作为页面。

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. 调整您的for语句并向后计数,这应该可以为您解决问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM