怎么删除数组中不需要的数据

如何删除数组中不需要的数据
  • 在开发中,由于某些需求,会将数组中不需要的数据进行删除。
  • 但是问题来了,数组在遍历的时候,不能移除。如何解决?
  • 解决的办法:创建一个新的删除数组,用来保存需要删除的对象

  • 我们一开始存储0~20:
 for (NSInteger index = 0 ; index < 20 ; index ++)
    {
        [self.total addObject:@(index)];
    }
  • 然后我们将能被2整除的放到另外一个数组中:
 [self.total enumerateObjectsUsingBlock:^(NSNumber * index, NSUInteger idx, BOOL * _Nonnull stop) {

        if (index.integerValue % 2 == 0)
        {
            [self.delete addObject:index];
            NSLog(@"%@",index);
        }
    }];
  • 然后我们要开始删除了
[self.delete enumerateObjectsUsingBlock:^(NSNumber *index, NSUInteger idx, BOOL * _Nonnull stop) {
        [self.total removeObject:index];
    }];

    [self.delete removeAllObjects];


    [self.total enumerateObjectsUsingBlock:^(NSNumber *index, NSUInteger idx, BOOL * _Nonnull stop) {
        NSLog(@"%@",index);
    }];

这样就能间接的删除了数组中不符合要求的数据