array delete operation

in conclusion

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.testArray = [NSMutableArray arrayWithObjects:@"cat",@"dog",@"man",@"dog",@"dog", nil];
    
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
//    [self removeObjectWithInset];
//    [self removeObjWithIndex];
//    [self removeObjWithObj];
//    [self removeObj];
//    [self removeTheObjWithInset];
    
    NSLog(@"%@",self.testArray);
}

/**
 delete by index
 */
- (void)removeObjWithIndex{
    for (int i = 0; i< self.testArray.count; i++) {
        NSString *var = self.testArray[i];
        if ([var isEqualToString:@"dog"]) {
            [self.testArray removeObjectAtIndex:i];
            // If you delete all isEqual obj, do not add Break
             // If you delete the first one, add break 
            break ;
        }
    }
}

/**
 Not adding break will cause crash
 Even adding break will delete all dogs
 */
- (void)removeObjWithObj{
    for (NSString *str  in self.testArray) {
        if ([str isEqualToString:@"dog"]) {
            [self.testArray removeObject:str];
            break;
        }
    }
}
/**
 It is also possible to delete it directly
 */
- (void)removeObj{
    [self.testArray removeObject:@"dog"];
}
/**
 Remove via NSInset
 */
- (void)removeObjectWithInset{
    NSIndexSet *indexSet  = [self.testArray indexesOfObjectsPassingTest:^BOOL(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        return [obj isEqualToString:@"dog"];
    }];
    
    [self.testArray removeObjectsAtIndexes:indexSet];
    
}
/**
 delete the second dog
 */
- (void)removeTheObjWithInset{
    NSMutableArray *idxArray = [NSMutableArray array];
    for (int i = 0; i< self.testArray.count; i++) {
        NSString *str = self.testArray[i];
        if ([str isEqualToString:@"dog"]) {
            [idxArray addObject: [NSString stringWithFormat:@"%d",i]];
        }
    }
    NSInteger getIndex;
    getIndex = [idxArray[1] integerValue];
    [self.testArray removeObjectAtIndex:getIndex];
}

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324516665&siteId=291194637
Recommended